2012-09-05 38 views
3

在一个页面上显示多个实体。对于每个实体都有一个谷歌地图。这是我怎么收拾显示地图只有一个实体:在一页上显示多个谷歌地图

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'); 
     } 
    }); 
} 

现在我想显示多个地图,每一个不同的位置。那看起来怎么样?有任何想法吗?该算法应该能够处理动态数量的实体。

回答

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'); 
     } 
    }); 
} 
+0

你是什么“的第二个参数//目标所需的地图”,其中第二个参数是什么意思? – inquisitive

+0

看起来像拼错:) –