2015-04-01 91 views
-2

如何刪除固定標記,將其添加到包含谷歌地圖的div元素中。下面的代碼行使用類'centerMarker',$('<div/>').addClass('centerMarker').appendTo(map.getDiv()); 添加它,但是如何刪除它(理想情況下使用Javascript)?從谷歌地圖中刪除固定標記

這裏是full JS Fiddle example其中添加了固定標記(從this stack overflow question)。 JS Fiddle示例中的代碼也顯示在下面。

HTML

<div id="map_canvas"></div> 

CSS

body,html,#map_canvas{height:100%;margin:0;} 
#map_canvas .centerMarker{ 
    position:absolute; 
    /*url of the marker*/ 
    background:url(http://maps.gstatic.com/mapfiles/markers2/marker.png) no-repeat; 
    /*center the marker*/ 
    top:50%;left:50%; 
    z-index:1; 
    /*fix offset when needed*/ 
    margin-left:-10px; 
    margin-top:-34px; 
    /*size of the image*/ 
    height:34px; 
    width:20px; 
    cursor:pointer; 
} 

的Javascript

function initialize() { 
     var mapOptions = { 
      zoom: 14, 
      center: new google.maps.LatLng(52.5498783, 13.425209099999961), 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     map = new google.maps.Map(document.getElementById('map_canvas'), 
      mapOptions); 
     $('<div/>').addClass('centerMarker').appendTo(map.getDiv()) 
      //do something onclick 
      .click(function(){ 
       var that=$(this); 
       if(!that.data('win')){ 
       that.data('win',new google.maps.InfoWindow({content:'this is the center'})); 
       that.data('win').bindTo('position',map,'center'); 
       } 
       that.data('win').open(map); 
      }); 
     } 

     google.maps.event.addDomListener(window, 'load', initialize); 
+0

'jQuery.remove' https://api.jquery.com/remove/只是好奇,但爲什麼你要被固定的標記(以便它獨立於地圖移動)? – Adam 2015-04-01 01:03:28

+0

@ user44776你有沒有找到解決方案,如果不給我更多關於你想做什麼的信息,所以我可以更新我的答案 – Ethaan 2015-04-01 05:20:32

回答

1

則可以使用GoogleMaps DOMEvents刪除,例如可以說,我們要刪除它的點擊(似乎更合適,因爲至少我們想在標記上顯示標記,如果不是,只需將其從中刪除即可js代碼)。

使用谷歌地圖API

Bassed在你的榜樣,只是添加此代碼,進入initialize功能

google.maps.event.addDomListener(map, 'click', removeMarker()); 

這裏是JSfiddle

如果你想提醒用戶爲什麼標記不見了,請使用一個函數,就像這樣。

function removeMarker(ele){ 
      ele.remove(); 
      alert('Ok the marker is GONE!') 
     } 
google.maps.event.addDomListener(map, 'click', removeMarker(this)); 

這裏是另一個JSFiddle的功能。

純JavaScript

如果你想刪除它與純JavaScript代碼初始化功能外,使用remove()方法類似的評論@Adam點,這樣的事情。

function removeMarker(elem){ 
    console.log('removed') 
     elem = document.getElementById("map_canvas"); 
     elem.childNodes[0].remove() 

} 
setTimeout(function(){ removeMarker(this) }, 3000); 

這裏是純JS JSFiddle