删除谷歌地图圆圈/形状

Removing a Google maps Circle/shape

本文关键字:形状 谷歌地图 删除      更新时间:2023-09-26

我正在使用google.maps.Circle()方法创建一个圆圈。这一切都很好用,但是我如何删除所述圆圈?

我的代码:

var populationOptionsAgain = {
  strokeColor: "#c4c4c4",
  strokeOpacity: 0.35,
  strokeWeight: 0,
  fillColor: "#ffffff",
  fillOpacity: 0.35,
  map: map,
  center: results[0].geometry.location,
  radius: 40000
};
cityCircle = new google.maps.Circle(populationOptionsAgain);
您需要将

Circle 对象上的 setMap 方法调用为 null:

cityCircle.setMap(null);

若要从映射中删除圆圈,请调用传递null作为参数的 setMap() 方法。

circle.setMap(null);

请注意,上述方法不会删除圆圈。它只是从地图中删除圆圈。如果您希望删除圆圈,则应将其从地图中移除,然后将圆圈本身设置为 null

https://developers.google.com/maps/documentation/javascript/shapes#circle_remove

您还需要删除事件侦听器,而不仅仅是隐藏圆圈,实际上circle.setMap(null)只会隐藏圆圈

function remove_circle(circle) {
    // remove event listers
    google.maps.event.clearListeners(circle, 'click_handler_name');
    google.maps.event.clearListeners(circle, 'drag_handler_name');
    circle.setRadius(0);
    // if polygon:
    // polygon_shape.setPath([]); 
    circle.setMap(null);
}

Google Maps API 已更新。您现在可以直接使用以下代码:

circle.remove();