2011-05-10 51 views
0

如何使用Javascript API v3在Google Map上获取多个标记?下面,当我的代码添加第二个标记时,它是删除第一个。如何在Google地图上显示2个标记?

var locations = { 
    "1" : { 
     "name": "location1", 
     "address": "10000 N Scottsdale Rd", 
     "city": "Scottsdale", 
     "state": "AZ", 
     "zipcode": "85253"            
    }, 
    "2" : { 
     "name": "location2", 
     "address": "15440 N 71st Street", 
     "city": "Scottsdale", 
     "state": "AZ", 
     "zipcode": "85254" 
    } 
}    
var geocoder = new google.maps.Geocoder(); 
for (item in locations) { 
    var loc = locations[item].address + ", " + locations[item].city + " " + 
     locations[item].state + " " + locations[item].zipcode; 
    geocoder.geocode({ 'address': loc}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var options = { 
       zoom: 10, 
       center: results[0].geometry.location, 
       mapTypeId: google.maps.MapTypeId.ROADMAP, 
       disableDefaultUI: true, 
       zoomControl: true 
      } 
      if (map) { 
       new google.maps.Marker({ 
        map: map, 
        position: results[0].geometry.location, 
        title: locations[item].name 
       });                  
      } else { 
       var map = new google.maps.Map(document.getElementById("map"), options); 
       new google.maps.Marker({ 
        map: map, 
        position: results[0].geometry.location, 
        title: locations[item].name 
       });         
      } 
      var infowindow = new google.maps.InfoWindow({ content: "test"}); 
     } else { // if map lookup fails, display a map of phoenix 
      var phoenix = new google.maps.LatLng(33.4483771,-112.07403729999999); 
      var options = { 
       zoom: 11, 
       center: phoenix, 
       mapTypeId: google.maps.MapTypeId.ROADMAP, 
       disableDefaultUI: true, 
       zoomControl: true 
      } 
      map = new google.maps.Map(document.getElementById("map"), options); 
     } 
    }); 
} 

回答

1

map变量只在回调函数定义(如function(results, status) {...}),所以当第二地理编码点回来,你还在创建一个新的地图(第二次),因为这map是未初始化。

您应该从标记添加代码中分别声明和初始化映射。

1

从您的数据集中循环显示标记结构。您的设置中的每个项目都会像平常一样创建一个标记。只需创建一次地图,并在创建标记时使用分配给它的变量。

相关问题