我有一张地图,它显示两个带有标记的位置(并自动在这两个位置之间居中),你可以在这里看到它:http: //goo.gl/rRDCE 我正在尝试将它与方向服务集成,就像这个演示:https ://developers.google.com/maps/documentation/javascript/examples/directions-simple
地图应该首先加载 2 个位置标记,然后如果用户选择一个起点,它应该显示到 2 个位置之一的方向。
这是我到目前为止所拥有的(当然不起作用,地图没有加载)......:P http://jsfiddle.net/multiformeingegno/fhAJA/5/
JAVASCRIPT
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var locations = [
['Place 1', 41.897467, 12.470364, 2],
['Place 2', 41.896561, 12.467792, 1]
];
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(17);
google.maps.event.removeListener(listener);
});
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
HTML:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<b>Start: </b>
<select id="start" onchange="calcRoute();">
<option value="chicago, il">Chicago</option>
<option value="st louis, mo">St Louis</option>
<option value="joplin, mo">Joplin, MO</option>
<option value="oklahoma city, ok">Oklahoma City</option>
<option value="amarillo, tx">Amarillo</option>
<option value="gallup, nm">Gallup, NM</option>
<option value="flagstaff, az">Flagstaff, AZ</option>
<option value="winona, az">Winona</option>
<option value="kingman, az">Kingman</option>
<option value="barstow, ca">Barstow</option>
<option value="san bernardino, ca">San Bernardino</option>
<option value="los angeles, ca">Los Angeles</option>
</select> <b>End: </b>
<select id="end" onchange="calcRoute();">
<option value="41.897467, 12.470364">Place 1</option>
<option value="41.896561, 12.467792">Place 2</option>
</select>
<div id="map" style="position:relative;width:500px;height:300px"></div>
我究竟做错了什么?:)