从Google地图中删除矩形

Dan*_*any 7 google-maps google-maps-api-3

我正在使用Google Maps v3(javascript).我加载地图时以下列方式绘制一个矩形:

<script type="text/javascript">
  // Global variables
  var map;

  /**
   * Called on the initial page load.
   */
  function init() {

    map = new google.maps.Map(document.getElementById('map'), {
      'zoom': 6,
      'center': new google.maps.LatLng(41.87194,12.567379999999957),
      'mapTypeId': google.maps.MapTypeId.ROADMAP
    });

    //Region Overlay
    var latLng1;
    var latLng2;

    <?php foreach ($this->arrRegion as $region) { ?>
        latLng1 = new google.maps.LatLng(<?php echo $region['boundLat1_region']; ?>,<?php echo $region['boundLng1_region']; ?>);
        latLng2 = new google.maps.LatLng(<?php echo $region['boundLat2_region']; ?>,<?php echo $region['boundLng2_region']; ?>);
        redraw(latLng1,latLng2);
    <?php }?>

  }

  /**
   * Updates the Rectangle's bounds to resize its dimensions.
   */
  function redraw(latLng1,latLng2) {
    var latLngBounds = new google.maps.LatLngBounds(latLng1,latLng2);
     // Create a new Rectangle overlay
    var rectangle = new google.maps.Rectangle({map: map, bounds: latLngBounds});
  }

  // Register an event listener to fire when the page finishes loading.
  google.maps.event.addDomListener(window, 'load', init);
</script>
Run Code Online (Sandbox Code Playgroud)

现在,我的目标是删除矩形.我尝试使用map.clear但它没有用.有什么建议吗?

Ton*_*ler 8

google.maps.Rectangle类有一个setMap方法.如果将null传递给它,则删除该矩形.请参阅http://code.google.com/apis/maps/documentation/javascript/reference.html#Rectangle

请注意,这意味着您需要保留矩形的实例,以便可以调用setMap方法.重绘函数中的局部矩形变量不会保留它,除非再次使用相同的latLng对重新调用重绘.