在一个页面上显示多个实体。对于每个实体,都有一个谷歌地图。这就是我如何处理只显示一个实体的地图:
var map;
var geocoder;
$(document).ready(function(){
google.maps.event.addDomListener(window, 'load', initialize);
});
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 16,
center: new google.maps.LatLng(50.317408,11.12915),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
codeAddress($('#entityID span#address').text());
}
function codeAddress(address) {
geocoder.geocode( {
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
codeAddress('germany');
}
});
}
现在我想要显示多个地图,每个地图都有不同的位置。那会是什么样子?有任何想法吗?该算法应该能够处理动态数量的实体。
答案 0 :(得分:6)
创建一个地图数组,如下所示:
var maps = []; // array for now
var geocoder;
$(document).ready(function(){
google.maps.event.addDomListener(window, 'load', initialize('map_1')); // two calls
google.maps.event.addDomListener(window, 'load', initialize('map_2'));
});
function initialize(_id) { // Map id for future manipulations
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 16,
center: new google.maps.LatLng(50.317408,11.12915),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
maps[_id] = new google.maps.Map(document.getElementById('map_canvas_'+_id), // different containers
mapOptions);
codeAddress($('#entityID span#address').text());
}
function codeAddress(address, map_id) {
geocoder.geocode( {
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: maps[map_id], // target nedded map by second parametr
position: results[0].geometry.location
});
} else {
codeAddress('germany');
}
});
}