且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Google Map删除HTML标记

更新时间:2023-12-05 22:45:22

您需要从DOM中删除div元素:

You need to remove the div element from the DOM:

HTMLMarker.prototype.onRemove = function () {
  div.parentNode.removeChild(div);
}

工作小提琴

代码段:

var overlay;
var htmlMarker;
var gmap;

function initialize() {
  var myLatLng = new google.maps.LatLng(62.323907, -150.109291);
  var mapOptions = {
    zoom: 11,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  gmap = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  htmlMarker = new HTMLMarker(62.323907, -150.109291);
  htmlMarker.setMap(gmap);
}
google.maps.event.addDomListener(window, 'load', initialize);

function HTMLMarker(lat, lng) {
  this.lat = lat;
  this.lng = lng;
  this.pos = new google.maps.LatLng(lat, lng);
}

HTMLMarker.prototype = new google.maps.OverlayView();
HTMLMarker.prototype.onRemove = function() {
  div.parentNode.removeChild(div);
}

//init your html element here
HTMLMarker.prototype.onAdd = function() {
  div = document.createElement('DIV');
  div.className = "htmlMarker";
  div.innerHTML = "<i>HTML Marker</i>";
  var panes = this.getPanes();
  panes.overlayImage.appendChild(div);
}

HTMLMarker.prototype.draw = function() {
  var overlayProjection = this.getProjection();
  var position = overlayProjection.fromLatLngToDivPixel(this.pos);
  var panes = this.getPanes();
  panes.overlayImage.style.left = position.x + 'px';
  panes.overlayImage.style.top = position.y - 30 + 'px';
}

html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<input type="button" value="toggle" onclick="if(htmlMarker.getMap()!=null) {htmlMarker.setMap(null)}else{htmlMarker.setMap(gmap);}" />
<div id="map_canvas"></div>