Link to home
Create AccountLog in
Avatar of mhdi
mhdi

asked on

Google Maps Javascript - Add listener to user created rectangle

Hi,

I have a google map that creates a rectangle when a user clicks on the map.

I now want to add a dblclick listener that removes the rectangle when a user double clicks on it. However because the rectangles are dynamically created, I do not know how to reference to them.

Any ideas?

http://jsbin.com/EXemIzU/1/edit?html,output

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Map</title>
	<script src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=geometry" type="text/javascript"></script>
</head>

<body class="" onload="load()" onunload="GUnload()">

		<div id="map" style="position:absolute; width: 1000px; height: 800px"></div>
</body>

<script type="text/javascript">

var rectangle;

function load() 
	{
			var latLng = new google.maps.LatLng(-37.799852,144.939823);
      
			map = new google.maps.Map(document.getElementById("map"),
			{
					center: latLng,
					zoom: 14,
					mapTypeId: google.maps.MapTypeId.ROADMAP
			}
			);

			 google.maps.event.addListener(map, 'click', function (event) 
			 {
                 var bounds = makeBounds(event.latLng, 400, 400 );  //get bounds of rectangle 400high 400 wide.
                 placeRec(bounds);
			 });
    }
	
  //Draw rectangle based on bounds
	function placeRec(bounds) {
			rectangle = new google.maps.Rectangle({
				strokeColor: '#FF0000',
				strokeOpacity: 0.8,
				strokeWeight: 2,
				fillColor: '#FF0000',
				fillOpacity: 0.35,
				map: map,
				editable:true,
				bounds: bounds
			  });
	  }
	
    //makeBounds creates LatLngBounds based on 1 latlng point.
	function makeBounds(nw, metersEast, metersSouth ) {
		var ne = google.maps.geometry.spherical.computeOffset(nw, metersEast, 90);
		var sw = google.maps.geometry.spherical.computeOffset(nw, metersSouth, 180);
		return new google.maps.LatLngBounds( sw, ne );
	}

</script>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of mhdi
mhdi

ASKER

Thankyou. Much simpler then I thought it was going to be.