troubleshooting Question

Google Maps Javascript - Add listener to user created rectangle

Avatar of mhdi
mhdi asked on
Web Languages and StandardsJavaScript
2 Comments1 Solution1312 ViewsLast Modified:
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>
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 2 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros