我正在尝试在同一页面上创建多个 map ,每个 map 具有不同的交通方向。
我已经能够迭代创建多个 Google map ,但无法在每个 map 中显示不同的方向。
我创建了许多保存 map 的 div,并为它们提供了 ID map-canvas1
、map-canvas2
、map-canvas3
>……等等。使用以下功能创建 map 后,如何在每个 map 中显示不同的交通方向?使用现在的代码,任何 map 中都不会出现任何方向(尽管每个 map 都会显示)。
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var coordinates;
function initialize(){
for (var i = 0; i < arrayOfObjects.length; i++){
var directionsDisplay = new google.maps.DirectionsRenderer();
var latitude = arrayOfObjects[i].latitude;
var longitude = arrayOfObjects[i].longitude;
coordinates = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 15,
center: coordinates
};
var numString = i.toString();
var thisMapID = "map-canvas" + numString;
map = new google.maps.Map(document.getElementById(thisMapID), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
};
}
var startingLocation = new google.maps.LatLng(40.768211, -73.957721);
function calcRoute(){
var request = {
origin: startingLocation,
destination: coordinates,
travelMode: google.maps.TravelMode.TRANSIT
};
directionsService.route(request, function(response, status){
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
}
});
}
最佳答案
独特的DirectionsRenederer需要与每个 map 相关联。请注意,DirectionsService 受到配额和速率限制,如果您有很多这样的 map ,您将必须检查返回状态并适当处理 OVER_QUERY_LIMIT 错误(您可能希望处理一般错误,因此服务会告诉您< em>为什么有些 map 不显示路线)。
var directionsDisplay = [];
var directionsService = [];
var map = [];
var coordinates;
function initialize(){
for (var i = 0; i < arrayOfObjects.length; i++){
directionsService[i] = new google.maps.DirectionsService();
directionsDisplay[i] = new google.maps.DirectionsRenderer();
var latitude = arrayOfObjects[i].latitude;
var longitude = arrayOfObjects[i].longitude;
coordinates = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 15,
center: coordinates
};
var numString = i.toString();
var thisMapID = "map-canvas" + numString;
map[i] = new google.maps.Map(document.getElementById(thisMapID), mapOptions);
directionsDisplay[i].setMap(map[i]);
calcRoute(i);
};
}
var startingLocation = new google.maps.LatLng(40.768211, -73.957721);
function calcRoute(index){
var request = {
origin: startingLocation,
destination: map[index].getCenter(),
travelMode: google.maps.TravelMode.TRANSIT
};
directionsService[index].route(request, function(response, status){
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay[index].setDirections(response);
} else { alert("Directions request failed: " + status); }
});
}
关于javascript - 您可以使用 Google Maps JavaScript API v3 在同一页面上显示多个带有路线的 map 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20366537/