谷歌地图:删除所有圈子

Lau*_*ren 2 javascript google-maps gmaps.js

我正在寻找一个 javascript 函数,它可以清除我地图上的所有绘图;类似于map.removeMarkers()or 的东西map.removeOverlays(),但对于形状 - 特别是圆形。

我已经看到了一些关于如何在 Android 上执行此操作的答案,但我正在寻找一个网络解决方案。我正在使用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
Run Code Online (Sandbox Code Playgroud)

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

Emm*_*lay 6

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

<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>
Run Code Online (Sandbox Code Playgroud)

编辑

一旦你有了这个数组,你就可以用它来打开/关闭,或者定位一些特定的圆圈,比如circkles[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>
Run Code Online (Sandbox Code Playgroud)