2015-04-01 69 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