Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Rectangle from Google Maps

I'm using Google Maps v3 (javascript). I draw a rectangle in the following way when I load my map:

<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>

Now, my goal is to remove the rectangle. I try to used map.clear but it didn't work. Any suggestion?

like image 898
Dany Avatar asked Mar 13 '12 16:03

Dany


People also ask

How do you delete a polygon in Google Maps?

To remove a polygon from the map, call the setMap() method passing null as the argument. In the following example, bermudaTriangle is a polygon object: bermudaTriangle. setMap(null);

How do I remove the HUD from Google Maps?

Disabling the UI Default Controls We can disable the default UI controls provided by Google Maps simply by making the disableDefaultUI value true in the map options.


1 Answers

The google.maps.Rectangle class has a setMap method. If you pass null to that, then the rectangle is removed. See http://code.google.com/apis/maps/documentation/javascript/reference.html#Rectangle

Note that this means that you need to keep instances of your rectangles around so that you can call the setMap method. The local rectangle variable in your redraw function will not keep it around, unless you call redraw wit the same latLng pairs again.

like image 195
Tony Miller Avatar answered Jan 04 '23 15:01

Tony Miller