源代码可以在某个地方使用,还是在那个精确的例子上有教程?
答案 0 :(得分:68)
以下是使用v3 API的一个非常基本的示例:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API v3 Directions Example</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">
<div style="width: 600px;">
<div id="map" style="width: 280px; height: 400px; float: left;"></div>
<div id="panel" style="width: 300px; float: right;"></div>
</div>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: 'Chicago',
destination: 'New York',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
</script>
</body>
</html>
截图:
答案 1 :(得分:1)
在 JavaScript 中使用 v3 API 使用纬度/经度或使用地址获取路线、路线和其他数据的代码:
<script src="https://maps.googleapis.com/maps/api/js?v=3&key=<key>&libraries=places"></script>
<script>
var directionsService = new google.maps.DirectionsService();
var start_lat = "41.8781136";
var start_lon = "-87.6297982";
var end_lat = "40.7127753";
var end_lon = "-74.0059728";
// Using Latitude and longitude
var request = {
origin: new google.maps.LatLng(start_lat, start_lon),
destination: new google.maps.LatLng(end_lat, end_lon),
optimizeWaypoints: true,
avoidHighways: false,
avoidTolls: false,
travelMode: google.maps.TravelMode.DRIVING
};
//Using plain address
// var request = {
// origin: { query: "Chicago, IL, USA" },
// destination: { query: "New York, NY, USA" },
// travelMode: google.maps.TravelMode.DRIVING,
// };
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
var leg = response.routes[0].legs[0];
var polyline = route.overview_polyline;
var distance = route.legs[0].distance.value;
var duration = route.legs[0].duration.value;
console.log(route); // Complete route
console.log(distance); // Only distance
console.log(duration); // Only duration
console.log(leg); // Route options/list
console.log(polyline); // Polyline data
}
});
</script>