getBounds of polygon

4,183 views
Skip to first unread message

hvr

unread,
Nov 10, 2009, 10:27:07 AM11/10/09
to Google Maps JavaScript API v3
Hi There,

I'm trying to dynamically draw a polygon on my map and i want to set
the zoom level so that no matter what the shape/size of the polygon it
will always be fully shown on the map. I've found instructions on how
to do this in V2 of the api but it seem that certain methods are
missing in V3. is there a new way to do this or has the functionality
not been added yet?

Tony

unread,
Nov 10, 2009, 11:38:11 AM11/10/09
to Google Maps JavaScript API v3
Try following psuedo code

var bounds = new google.maps.LatLngBounds();
var points = [];
var point;
var polygon;

//Create array of points defining your polygon
for each point on your polygon...
point = new google.maps.LatLng(<lat>,<lng>);
bounds.extend(point);
points.push(point):

polygon = new google.maps.Polygon({
paths: points,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});

polygon.setMap(map);

//Then fit the map to your bounds object
map.fitBounds(bounds);

hvr

unread,
Nov 10, 2009, 1:16:49 PM11/10/09
to Google Maps JavaScript API v3
Thanks for this! I was thinking of doing something similar. I'm
going to try to get the bounds on the server side and pass them to the
client.

arclyte

unread,
Nov 10, 2009, 4:36:17 PM11/10/09
to Google Maps JavaScript API v3
I'm using MySQL's Spatial Extensions. It has the Envelope() function
that returns an MBR for the given geometry. You could use that to
easily extract the points you need for set for fitBounds(). I don't
know what you're using to store your geo data, but I believe most
spatially-aware databases have similar functions.

SELECT AsText(Envelope(geometry));
returns (MINX MINY, MAXX MINY, MAXX MAXY, MINX MAXY, MINX MINY)
grab the first and third coordinates in the return and use them as
your lat/lng for fitBounds();

I haven't actually implemented this yet, but I think it'd be quicker
to load than doing the processing on the client side or even in a loop
over the points server-side.
Reply all
Reply to author
Forward
0 new messages