Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

Chapter 9 — Using Overlays 173


Calculating Where to Center the Map


The final stage of moving the map to the location of the city that is being displayed is to deter-
mine a suitable point that can be used as the new center point for the map.


You could choose to display one of the restaurants as the new center point, but a much more
effective method is to calculate the middle point between the extremes of latitude and longi-
tude for the displayed markers. Essentially what you are after is the average, or more specifi-
cally the median, of the range of points.


There is no simple way of achieving this, although you could potentially ask the database to
determine the information. Because this would imply further processing of data that you
already have, it is just as easy to calculate it from that data. You can find the midpoint by deter-
mining the difference between the highest and lowest value and adding half the difference to
the lower value. To determine the lowest and highest values, use the following logic: If the lati-
tude and longitude points for each marker are added to an array and the array is sorted, the
minimum and maximum values will be the first and last values in the array, respectively.


Listing 9-19 performs these operations, returning a new GPoint()to the caller that can be
used to recenter the map.


Listing 9-19: Determining a New Center Point

function calccenter(latpoints,lngpoints) {
latpoints.sort();
lngpoints.sort();
var newlat = latpoints[0] + ;
((latpoints[latpoints.length-1] - latpoints[0])/2);
var newlng = lngpoints[0] + ;
((lngpoints[lngpoints.length-1] - lngpoints[0])/2);
var newpoint = new GPoint(parseFloat(newlng),parseFloat(newlat));
return newpoint;
}


The last stage to the process is initializing the entire system so that the application is in a state
ready to start accepting user clicks.


Initializing the Map


In previous examples, the onLoad()function has been quite complex. For this example,
the main part of the initialization in terms of providing interactivity now resides in the
showcitylist()function. The main role of the onLoad()function, shown in Listing
9-20, is to initialize the map and obtain the location of the HTML elements that will be used
to show information about the application, such as the message and information window.

Free download pdf