Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

186 Part III — Google Map Hacks


Centering and Deciding on a Zoom Level
One of the problems with any map is ensuring that the view the user gets (initially, at least) con-
tains all of the information you are trying to portray. Chapter 9 showed centerAndZoom(),a
simple function that calculates the center point of all of the points being displayed. The limitation
of this function is that it relies on using a generic zoom level, which may or may not be suitable
for the points and markers being displayed on the map.

The recenterandzoom()function performs the same centering process, but this time it
accepts a single argument, an array of points. To determine the midpoint, the latitude and lon-
gitude of each point are extracted and then added to their own array, which is then sorted, and
the same calculation as before determines the center-point of all the supplied points for center-
ing the map.

By comparing the span of the points (the difference between the maximum and minimum val-
ues), the function can determine an ideal zoom level by trying out zoom levels until a level that
encompasses the span of the points is found. To do this, it iterates from the highest zoom level
to the lowest and uses the getSpanLatLng()method to compare the point span with the
span displayed on the active map. If the displayed span is smaller than the required span, the
map zooms out by one level and the values are re-checked until a zoom level and span combi-
nation are determined.

To ensure that the span incorporates a small buffer (so points don’t appear on the edges of the
map), the actual span required is increased by 25 percent before the determination is made:
function recenterandzoom(points) {
var latpoints = [];
var lngpoints = [];

var idealzoom = 1;
// Do nothing if no points supplied
if (points.length == 0) {
return;
}
// Zoom right in if just one point is supplied
if (points.length == 1) {
map.centerAndZoom(points[0],idealzoom);
return;
}

for(var i=0;i<points.length;i++) {
latpoints.push(points[i].y);
lngpoints.push(points[i].x);
}
// Sort, enforcing a numerical comparison
latpoints.sort(function(x,y) { return x-y });
lngpoints.sort(function(x,y) { return x-y });

var newlat = latpoints[0] + ((latpoints[latpoints.length-1] - ;
latpoints[0])/2);
Free download pdf