2013-02-15 71 views
0

我有一個小功能,點擊時添加一個標記和信息窗口。但是,當我點擊一個新位置時,舊位置仍然存在。我希望它被新的替代。這裏是我的代碼:谷歌地圖apiv3標記替換舊

function MapInitialize() { 

      var mapOptions = { 
      zoom: 4, 
      center: new google.maps.LatLng(43,-77), 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
      } 

      var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 
     google.maps.event.addListener(map, 'click', function(event) { 
      var marker = new google.maps.Marker({ 
       position: event.latLng, 
       map: map 
     }) 
     var infowindow = new google.maps.InfoWindow({ 
       content: 'Content Here' 
      }); 
      infowindow.open(map,marker); 
}); 
} 

謝謝!

回答

1

創建之前刪除舊的標記新一:

var marker = null; 
function MapInitialize() { 

      var mapOptions = { 
      zoom: 4, 
      center: new google.maps.LatLng(43,-77), 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
      } 

      var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 
     google.maps.event.addListener(map, 'click', function(event) { 
      if (marker && marker.setMap) marker.setMap(null); 
      marker = new google.maps.Marker({ 
       position: event.latLng, 
       map: map 
     }) 
     var infowindow = new google.maps.InfoWindow({ 
       content: 'Content Here' 
      }); 
      infowindow.open(map,marker); 
}); 
} 
+0

謝謝你,這對我的作品 – 2013-02-15 16:51:47