var map;
var geocoder;
var origin = "Aeroporto da Madeira"
var destinations = [
"Hotel Four Views Baía, Rua das Maravilhas, Funchal",
"R. José Joaquim da Costa 112, 9325-031 Estreito De Câmara, Portugal",
"Q.ta de São João, 2735-521, Portugal"
];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin], //array of origins
destinations: destinations, //array of destinations
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
//we only have one origin so there should only be one row
var routes = response.rows[0];
//need to find the shortest
var lowest = Number.POSITIVE_INFINITY;
var tmp;
var shortestRouteIdx = -1;
var resultText = "Possible Routes: <br/>";
for (var i = routes.elements.length - 1; i >= 0; i--) {
//do we got a result for the element?
if (routes.elements[i].status === google.maps.DistanceMatrixElementStatus.OK) {
tmp = routes.elements[i].duration.value;
resultText += "Route " + destinations[i] + ": " + tmp + "<br/>";
if (tmp < lowest) {
lowest = tmp;
shortestRouteIdx = i;
}
}
}
//log the routes and duration.
document.getElementById('results').innerHTML = resultText;
if (shortestRouteIdx > -1) {
//get the shortest route
var shortestRoute = destinations[shortestRouteIdx];
//now we need to map the route.
calculateRoute(origin, shortestRoute)
} else {
alert('no route available');
}
}
}
//Calculate the route of the shortest distance we found.
function calculateRoute(start, end) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var centerPosition = new google.maps.LatLng(32.670159, -16.978268);
var options = {
zoom: 12,
center: centerPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), options);
directionsDisplay.setMap(map);
calculateDistances();
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#results {
position: fixed;
top: 0;
right: 0;
background: gold;
}
<div id="map"></div>
<div id="results"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
你有一个错误在控制台(遗漏的类型错误:无法读取的未定义的属性“值”)在该行(TMP = routes.elements [I] .duration.value;),所以它看起来像值未设置 – Tasos
酒店Four视图Baía不是有效的地址,可能无法准确定位。 – geocodezip