Google Maps Javascript - Limit to one rectangle

Hi,

I have a google map that lets the user add rectangles by clicking on the map. Currently users can add multiple rectangles.

I want to limit it to one rectangle.

If the user tries to add a second rectangle, the first rectangle should be removed automatically.

Is this possible?

http://jsfiddle.net/cf9CF/

 
var latLng = new google.maps.LatLng(-37.81987,144.968398);
map = new google.maps.Map(document.getElementById("map"),
{
		center: latLng,
		zoom: 17,
		mapTypeId: google.maps.MapTypeId.ROADMAP
}
);

google.maps.event.addListener(map, 'click', function (event) 
 {
	var bounds = makeBounds(event.latLng, 100, 100 );
	placeRec(bounds);
 });

function placeRec(bounds) {
	var rectangle = new google.maps.Rectangle({
		strokeColor: '#FF0000',
		strokeOpacity: 0.8,
		strokeWeight: 2,
		fillColor: '#FF0000',
		fillOpacity: 0.35,
		map: map,
		editable:true,
		options: {draggable:true},
		bounds: bounds
	});
}

Open in new window

mhdiAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
test page : http://jsfiddle.net/cf9CF/1/

    var rectangle = null;
    //Draw rectangle based on bounds
    function placeRec(bounds) {
        if(rectangle) rectangle.setMap(null);
        rectangle = new google.maps.Rectangle({
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35,
            map: map,
            editable:true,
            bounds: bounds
        });
		 google.maps.event.addListener(rectangle, 'dblclick', function (event) {
			 this.setMap(null);
            rectangle = null;
		 });
    }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.