Using fitBounds and LatLngBounds as a Smart Zoom Feature

1,309 views
Skip to first unread message

drumat5280

unread,
Jul 14, 2009, 4:24:17 PM7/14/09
to Google Maps JavaScript API v3
I started trying to figure out a way to let my users set the zoom
level and map center for their own maps on this page:

http://www.pickrent.com/map/pickmap.cfm

As I was trying to figure it out I ran across fitBounds and
LatLngBounds methods in V3.

So instead of letting the user do the work I thought there might be an
easy way to let the API do the work for them by zooming in and
centering the map for them based off their rental property locations.

I have found very little written on these methods and have little idea
where to place them in the JS code to make this work.

Where can I place these methods to create a "Smart Zoom" feature?

Thanks,
Dave

Esa

unread,
Jul 15, 2009, 4:58:09 AM7/15/09
to Google Maps JavaScript API v3
First in the beginning declare an empty LatLngBounds (it can be the
first line in your initialize() function):

var markerBounds = new google.maps.LatLngBounds();

Then every time you add a marker (in your attachInfo() function)
extend the LatLngBounds object by the LatLng of the marker:

markerBounds.extend(myLatLng);

After all the markers are set (the last line in your initialize()
function):

map.fitBounds(markerBounds);

drumat5280

unread,
Jul 15, 2009, 6:20:40 PM7/15/09
to Google Maps JavaScript API v3
Esa,

Thank you so much for helping me out.

I tried your suggestion and I am not sure I placed each of the 3 lines
in the right spot because I am getting an error using Firebug
indicating that "markerBounds is not defined" - also only one of the
dozen or so markers made it to the map:

"markerBounds is not defined
attachInfo(Object Oa=Object Vb=Object center=(39.967052, -104.835789),
["1256 Lark Ave.", 39.967052, -104.835789, 1 more... 0=1256 Lark Ave.
1=39.967052 2=-104.835789])pickmap.cfm (line 294)
setMarkers(Object Oa=Object Vb=Object center=(39.967052, -104.835789))
pickmap.cfm (line 275)
initialize()pickmap.cfm (line 64)
onload(load )"

I tried moving that line around in different locations within the
function but didn't have any luck.

Any other suggestions?

Thanks!
Dave

Esa

unread,
Jul 15, 2009, 8:18:52 PM7/15/09
to Google Maps JavaScript API v3
Sorry, I gave a bad advice to declare the var markerBounds inside your
initialize function. The variable should be global because that is
later called by another function.

To make it global, declare it as a property of window object. Instead
of:

var markerBounds = new google.maps.LatLngBounds();

try:

window.markerBounds = new google.maps.LatLngBounds();

I think we have a better chance with that.

Dave Dugdale

unread,
Jul 16, 2009, 12:52:15 AM7/16/09
to Google Maps JavaScript API v3
Esa,

Thanks! That worked perfectly!

Thank you!
Dave
Reply all
Reply to author
Forward
0 new messages