javascript 使用纬度/经度的谷歌地图方向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4163726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google map direction using lat/lon
提问by coure2011
I have lat/lon for 2 places. How to get directions from google maps api? I want to show map and directions text.
我有 2 个地方的经纬度。如何从谷歌地图 api 获取路线?我想显示地图和路线文本。
回答by iRyanBell
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
var start = '37.7683909618184, -122.51089453697205';
var end = '41.850033, -87.6500523';
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myRoute = response.routes[0];
var txtDir = '';
for (var i=0; i<myRoute.legs[0].steps.length; i++) {
txtDir += myRoute.legs[0].steps[i].instructions+"<br />";
}
document.getElementById('directions').innerHTML = txtDir;
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="directions" style="width:500px;height:500px;float:left"></div>
<div id="map_canvas" style="width:500px;height:500px;"></div>
</body>
</html>
回答by vinyll
Or using the previous code :
或者使用之前的代码:
…
var start = new google.maps.LatLng('37.7683909618184', '-122.51089453697205');
var end = new google.maps.LatLng('41.850033', '-87.6500523');
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
…
}
…
This way the coordinates are directly recognized as such, and not evaluated from string.
这样坐标就直接被识别了,而不是从字符串中计算出来的。
回答by aristotll
Yet another solution: pass an object like to origin and destination
另一个解决方案:传递一个对象,如 origin 和 destination
{lat: 39.904309, lng: 116.385871}

