Calculate and Set Bounds (Bounding Box) from Points in Google Maps Flash [Update]

I’ve got a list of points in my database, which I want to show neatly in a Google Maps Flash Map.

Thus, I …

  1. calculate the bounding box around these points
  2. calculate the center of this bounding box
  3. set the zoom level of the map in a way that the zoomed cutout contains all points
  4. set the center of the map
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//1.
var bounds:LatLngBounds = new LatLngBounds();
for each(var mapObject in tripMessages){
    var currentLatLon:LatLng = new LatLng(mapObject.latitude, 
	                                       mapObject.longitude);
    bounds.extend(currentLatLon);
}
 
//2.
var center:LatLng = bounds.getCenter();
 
//3.
map.setZoom(map.getBoundsZoomLevel(bounds));
 
//4.
map.setCenter(center);
Posted in Actionscript, Adobe Air, Flash, flex Tagged with: Actionscript, Flash, google maps
  • Hi there,

    There’s no need to fo all those 4 IFs to test for the min/max lat/lon, as there is a methot for the LatLngBounds object that does that for you:

    bounds.extend(Point);

    Along the same idea, there is no need to compute the center, as it also has a method:

    bounds.getCenter();

    So all you have to do is define the LatLngBounds object, add the points to it using the extend method, and at the end, just call getBoundsZoomLevel and getCenter to obtain what you need.

    Regards,
    Emil

  • Wow, Emil, you have been completely right!

    I changed the code appropriately and now it is much shorter.

    However, I still have the same problem with that code that I had with the other code before: sometimes the bounding box will not be calculated appropriately and is one zoom step too small. I don’t know whether that is a problem of the code or of the Google Maps API as I don’t know how map.getBoundsZoomLevel(bounds) works.

  • Thanks so much for this bit of code -saved me hours

  • hello ,
    i want a help from you i want to set bounds for my map on a particular marker keeping it in center and start drawing a polyline.
    once the polyline reaches the bounds,then the bounds get automatically update or change.
    how to achive all this please help me .
    thank you.

  • hi neelb2neel,
    i am sorry to say that i have not been able to completely grasp what you want to know from me. could you give me some more information, please!