Google Maps Directions API经纬度参数使用异常求助
Google Maps Directions API 经纬度起点路线异常排查
问题现象
根据Google Maps Directions API官方文档,起点(origin)与终点(destination)字段支持使用经纬度值获取路线,但实际使用中遇到以下异常:
- 使用地址格式时功能正常
- 若起点为经纬度值、终点为地址格式,会生成完全错误的路线
- 两者均为地址格式时路线显示正常
相关代码
<html> <head> <title>Routes</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <div id="map" style="height:50%; width:75%"></div> <script src=" https://maps.googleapis.com/maps/api/js?key=APIKEY"></script> <script src="app.js"></script> <div class="pac-card" id="pac-card"> <div> <div id="title"><b></b></div> <div style="display: none" id="type-selector" class="pac-controls"> <input type="radio" name="type" id="changetype-all" checked="checked" /> <label for="changetype-all">All</label> </div> <br /> <div style="display: none" id="strict-bounds-selector" class="pac-controls"> <input type="checkbox" id="use-location-bias" value="" checked /> <label for="use-location-bias">Bias to map viewport</label> <input type="checkbox" id="use-strict-bounds" value="" /> <label for="use-strict-bounds">Strict bounds</label> </div> </div> <p id="pkup"><?php echo $_POST['pkup']; ?></p> <p id="dest"><?php echo $_POST['destination']; ?></p> <p id="total"></p> </div> </div> <div id="map"></div> <div id="infowindow-content"> <span id="place-name" class="title"></span><br /> <span id="place-address"></span> </div> <script type="text/javascript"> function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: { lat: 7.3782, lng: 3.9062 }, // Osogbo Nigeria. }); const directionsService = new google.maps.DirectionsService(); const directionsRenderer = new google.maps.DirectionsRenderer({ draggable: true, map, panel: document.getElementById("panel"), }); directionsRenderer.addListener("directions_changed", () => { const directions = directionsRenderer.getDirections(); if (directions) { computeTotalDistance(directions); } }); var pkup=document.getElementById("pkup").innerHTML; var dest=document.getElementById("dest").innerHTML; displayRoute( "Osogbo, Nigeria", dest, directionsService, directionsRenderer ); } function displayRoute(origin, destination, service, display) { service .route({ origin: origin, destination: destination, travelMode: google.maps.TravelMode.DRIVING, avoidTolls: true, }) .then((result) => { display.setDirections(result); }) .catch((e) => { alert("Could not display directions due to: " + e); }); } function computeTotalDistance(result) { let total = 0; const myroute = result.routes[0]; if (!myroute) { return; } for (let i = 0; i < myroute.legs.length; i++) { total += myroute.legs[i].distance.value; } total = total / 1000; document.getElementById("total").innerHTML = total + " km"; } window.initMap = initMap; </script> <script src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap&libraries=places&v=weekly" defer ></script> </body> </html>
问题原因排查
- 经纬度格式解析错误:直接将DOM获取的经纬度字符串传给API,若字符串格式不规范(如存在多余空格、分隔符错误),API无法正确解析坐标,导致定位偏差。
- 重复地图容器冲突:页面存在两个
id="map"的div元素,地图初始化仅绑定第一个容器,路线渲染可能出现异常。 - API重复加载冲突:页面两次引入Google Maps JS API,无defer的脚本会提前加载,与带callback的defer脚本产生冲突,影响功能运行。
- 未使用推荐的坐标格式:Google Maps API优先支持
{lat: 数值, lng: 数值}的对象格式,字符串格式要求严格的"纬度, 经度"格式,否则易解析失败。
修复方案
1. 修正经纬度传递方式
将获取的经纬度字符串转换为API支持的对象格式:
function initMap() { // ... 其他代码不变 ... var pkupStr = document.getElementById("pkup").innerHTML.trim(); // 拆分经纬度,确保格式为 "lat,lng" var coordParts = pkupStr.split(',').map(item => parseFloat(item.trim())); var origin = { lat: coordParts[0], lng: coordParts[1] }; var dest = document.getElementById("dest").innerHTML.trim(); displayRoute(origin, dest, directionsService, directionsRenderer); }
2. 清理重复元素与脚本
- 删除页面中多余的
<div id="map"></div>容器,只保留一个。 - 删除重复的API引入行:
<script src=" https://maps.googleapis.com/maps/api/js?key=APIKEY"></script>,仅保留带有defer、callback和libraries的那一行。
3. 验证后端传递的经纬度格式
确保后端$_POST['pkup']传递的是严格格式的经纬度字符串,例如"7.3782, 3.9062",无多余字符或空格。
内容的提问来源于stack exchange,提问作者Ayo Owoade
相关产品推荐
相关产品推荐

