user1724365
user1724365

Reputation: 97

Google maps user editable polygon

Using Google maps API V3, specifically using the drawing tools (only the rectangle is enabled) as seen here:

https://developers.google.com/maps/documentation/javascript/overlays#drawing_tools

But I have the following question,

  1. Can I (if so how), by action of the user clicking a link on the same page, retrieve the lat,lng of the top left corner of the polygon and the bottom right, and send to a url, ie;

http://foo.bar/script.php?latoftopleft=17.4479216&longoftopleft=78.37720100000001&latofbotright=17.443172404867163&longofbotright=78.39395944192506

Upvotes: 1

Views: 2811

Answers (1)

Andrew
Andrew

Reputation: 2780

Retrieving the Rectangle

One way to retrieve the rectangle drawn by the user is to use Drawing Events:

var rectangle;
google.maps.event.addListener(drawingManager, 'rectanglecomplete', function(newRect) {
    rectangle = newRect;
});

Whenever a rectangle is drawn by the user, it will assign the Rectangle overlay object to the rectangle global variable.

Extracting information about the Rectangle

The google.maps.Rectangle class has a getBounds() method, which returns a LatLngBounds object. You can use the getNorthEast() and getSouthWest() methods to deduce the top-left and bottom-right corner coordinates.

You can bind an onclick event to the link. The click event handler might look something like this:

function clickEventHandler(event) {
    // check if the rectangle has been assigned
    if (rectangle == undefined) {
        alert('No rectangles have been drawn yet!');
        return;
    }

    // obtain the bounds and corner coordinates of the rectangle
    var rectangleBounds = rectangle.getBounds();
    var northEast = rectangleBounds.getNorthEast();
    var southWest = rectangleBounds.getSouthWest();

    // deduce the top-left and bottom-right corner coordinates
    var topLeft = new google.maps.LatLng(northEast.lat(), southWest.lng());
    var bottomRight = new google.maps.LatLng(southWest.lat(), northEast.lng());

    // Now that you have the coordinates, all you have to do is use an AJAX
    // technique of your choice to send the HTTP request to script.php.
    // ...
}

Further reading:

Upvotes: 2

Related Questions