如何将Node.js的Location坐标数组传递至Google Maps JS API绘图
解决Node.js端坐标数组传递到前端Google Maps API的方案
1. 后端路由传递坐标数组到EJS模板
在渲染地图页面的GET路由中,将存储坐标的Location数组作为模板变量传给EJS:
// 假设你的坐标数组存储在全局或数据库,这里用app.locals示例 app.get('/map', (req, res) => { // 初始化空数组防止报错 const flightCoords = req.app.locals.locations || []; // 将坐标数组传给EJS模板 res.render('map', { flightCoords }); });
2. 处理POST提交并更新坐标数组
在/plot的POST路由中,接收表单提交的经纬度,更新数组后重定向回地图页面:
app.post('/plot', (req, res) => { // 解析表单提交的经纬度,转成数字类型 const newCoordinate = { lat: parseFloat(req.body.lat), lng: parseFloat(req.body.lng) }; // 初始化全局坐标数组(首次提交时) if (!req.app.locals.locations) { req.app.locals.locations = []; } // 添加新坐标到数组 req.app.locals.locations.push(newCoordinate); // 重定向回地图页面,触发GET路由渲染最新坐标 res.redirect('/map'); });
3. 前端EJS模板注入坐标数组到Google Maps代码
在EJS的地图页面中,用EJS语法直接将后端传递的数组注入到initMap函数中,替换原有的flightPlanCoordinates:
<div id="map" style="height: 400px; width: 100%;"></div> <script> function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 10, // 可以用数组第一个坐标作为地图中心,避免固定坐标 center: <%- flightCoords.length ? JSON.stringify(flightCoords[0]) : '{ lat: 0, lng: 0 }' %>, mapTypeId: "terrain", }); // 直接注入后端传递的坐标数组 const flightPlanCoordinates = <%- JSON.stringify(flightCoords) %>; const flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2, }); flightPath.setMap(map); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
关键注意事项
- 使用
<%- %>而非<%= %>输出数组:前者会直接输出原始JSON内容,避免HTML转义导致的JS语法错误 - 确保坐标格式符合Google Maps要求:每个元素必须是
{lat: 数字, lng: 数字}的结构 - 如果用数据库存储坐标,需在GET路由中查询最新数据再传递给模板,而非依赖全局变量
- 表单提交的经纬度是字符串类型,必须转成数字后存入数组,否则地图无法识别
内容的提问来源于stack exchange,提问作者Mohamed Radwan
相关产品推荐
相关产品推荐

