谷歌地图:删除所有圆圈

Google Map: Remove all Circles

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

我正在寻找一个javascript函数,将清除所有图纸从我的地图;例如map.removeMarkers()map.removeOverlays(),但用于形状-特别是圆形。

我已经看到了一些关于如何在Android上做到这一点的答案,但我正在寻找一个web解决方案。我用gmaps.js来画圆圈:

// create circle loop
for( i = 0; i < data.mapArray.length; i++ ) {
    circle = map.drawCircle({
        lat: data.mapArray[i].lat,
        lng: data.mapArray[i].lng,
        radius: parseInt(data.mapArray[i].radius),
        strokeColor: '#'+data.mapArray[i].color,
        strokeWeight: 8,
        fillOpacity: 0,
        click: (function (e) {
            return function () {
                $('#'+modalType).modal({
                    remote: modalURL+e
                });
            };
        })(data.mapArray[i].id)
    });
} // end loop

我猜在这个循环中,我需要将圆圈添加到数组中,然后调用一个函数来清除所有圆圈,但我不确定如何执行

一个简单的解决方案是将对象存储在数组

<input type="button" value="Clear all" onclick="removeAllcircles()"/>
<script>
var circles = [];
// create circle loop
for( i = 0; i < data.mapArray.length; i++ ) {
    var circle = map.drawCircle({
        lat: data.mapArray[i].lat,
        lng: data.mapArray[i].lng,
        radius: parseInt(data.mapArray[i].radius),
        strokeColor: '#'+data.mapArray[i].color,
        strokeWeight: 8,
        fillOpacity: 0,
        click: (function (e) {
            return function () {
                $('#'+modalType).modal({
                    remote: modalURL+e
                });
            };
        })(data.mapArray[i].id)
    });
    // push the circle object to the array
    circles.push(circle);
} // end loop
// remove All circles
function removeAllcircles() {
  for(var i in circles) {
    circles[i].setMap(null);
  }
  circles = []; // this is if you really want to remove them, so you reset the variable.
}
</script>

编辑

一旦你有了这个数组,你就可以使用它来切换开/关,或者针对一些特定的圆,比如圆圈[17]…

<input type="button" value="Toggle on" onclick="toggleOn()"/>
<input type="button" value="Toggle off" onclick="toggleOff()"/>
<script>
// Toggle off
function toggleOff() {
  for(var i in circles) {
    circles[i].setMap(null);
  }
}
// Toggle on
function toggleOn() {
  for(var i in circles) {
    circles[i].setMap(map);
  }
}
</script>

觉得这段代码更简单一点。

var circles = [];
// create circle loop
for( i = 0; i < data.mapArray.length; i++ ) {
    circle = map.drawCircle({
        lat: data.mapArray[i].lat,
        lng: data.mapArray[i].lng,
        radius: parseInt(data.mapArray[i].radius),
        strokeColor: '#'+data.mapArray[i].color,
        strokeWeight: 8,
        fillOpacity: 0,
        click: (function (e) {
            return function () {
                $('#'+modalType).modal({
                    remote: modalURL+e
                });
            };
        })(data.mapArray[i].id)
    });
    circles.push(circle);
} // end loop

当需要删除时,只需执行…

circles.forEach((circle) => {
    circle.setMap(null);
});
circles = [];