My Blog of Japan Japan!

Posted
27 September 2007 @ 8pm

Posted In:
Google Maps, PHP, Programming

Setting size and zoom level of maps

What I though was going to be an easy case of looking through the google maps API for a solution to bounds turned into a mammoth task today. I wanted a way to make the centre and zoom of a map change according to the points it contained, with the centre being the average of the North-South and East-West extremes, and the zoom being wide enough to fit all points, but not too wide that it squished up all the points in the centre of the map. Before, I had randomly set the centre and zoom so that it showed most of Tokyo and Chiba, where most of my points were. But what if I took a trip to Hokkaido? That would leave one of the points invisible to this map.

In the google maps API, there’s a getBounds call, which returns the current boundaries of your map. So I assumed that there’d also be a setBounds, which would set the boundaries. No such luck.. I found lots of setBounds, but they all seemed to be for other APIs, and none of them would work with my map. In the end, I found someone with a similar problem at the Google Maps API Group. They used the getBoundsZoomLevel function call to sort it out.

I solved the problem first in PHP like this: I put all the latitude coordinates into an array called $latitudes, then did a min($latitudes) and max($latitudes). Then the same for longitudes. Both these arrays had been collected while I was searching for valid photos to use on the front page. Then I plugged the min and max values into this javascript (with the PHP variables mixed in):


function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
var bounds = new GLatLngBounds;
bounds.extend(new GLatLng(<?php echo $South, $West; ?>));
bounds.extend(new GLatLng(<?php echo $North, $East; ?>));
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
// output the markers here.
}
}

All thanks to Dominique on this thread.

I tidied up the marker making too, by putting the create location and
create marker code together, cutting down the size and complexity. Now they look like this:
var marker_1 = new GMarker(new GLatLng(35.659370956361, 140.11903345585));
map.addOverlay(marker_1);

Edit: This guy had the same problem

http://www.soulcast.com/post/show/65110/google-maps-api—dynamically-selecting-zoom-and-center-point


No Comments Yet


There are no comments yet. You could be the first!

Leave a Comment

Hardcore Chamber Music Writing Screen Scrapers - Extract Information the Painless Way