2011-05-10 145 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

從您的數據集中循環顯示標記結構。您的設置中的每個項目都會像平常一樣創建一個標記。只需創建一次地圖,並在創建標記時使用分配給它的變量。

相關問題