190 Part III — Google Map Hacks
To keep the height of each bar consistent, you need a baseline to work from. Using a percent-
age value, rather than the real value, keeps the height of the bars consistent across different data
values. You can use the combination of the current map view and the percentage value of the
data point to keep the bar height consistent within the available view. Because that value is a
percentage, the size of the map can be divided by 100 and then by a further value (to ensure the
graph is displayed within the map) to determine the latitude increment to use when drawing
each bar.
The code for this is called when a user clicks a specific year in the list of available years. The
code performs a number of steps to achieve the goal. The first is to calculate the increment to
be used for drawing each tick on the bar graph:
function addgraph(year) {
var currentsize = map.getSpanLatLng();
var increment = (parseFloat(currentsize.height)/2.0)/100;
var maxsize = 0;
var graphdata = [];
The existing data and overlays are cleared from the map, and the information panel is also
emptied because the data in the panel will be regenerated to include the population data:
map.clearOverlays();
polylines = [];
markers = [];
infopanel.innerHTML = ‘’;
Now the graphdatafor the selected year is extracted into a single array, and the maximum
size of the data is determined. A marker for each city is generated (using a modified
addmarker()function) that also embeds the city name and population value into an
InfoWindowfor each marker:
for(var i=0;i<popdata.length;i++) {
graphdata.push(popdata[i][year]);
if (popdata[i][year] > maxsize) {
maxsize = popdata[i][year];
}
addmarker(points[i].x,points[i].y,titles[i] + ‘; Pop: ‘ +
popdata[i][year] + ‘ in ‘ + year);
}
Finally, each bar is created by creating an array of points, with just two elements. The starting
point is the location of each city, which is held in the global points array. The second point is
the longitude of the city (which does not change). The latitude value is used to create the
height of the bar. That value can be calculated, first, by multiplying the percentage of the data
point by the increment calculated for the map. If you then add that value to the latitude of the
city, you get a new latitude that represents bar size. The resulting two-point array is used to cre-
ate a polyline, where the color is explicitly specified along with a wider than normal point
width so that the bar shows up clearly on the map:
for(var i=0;i<graphdata.length;i++) {
var pointpair = [];
pointpair.push(points[i]);
var secondlatinc = ((parseFloat(graphdata[i])*100)/maxsize)*increment;
var secondlat = (parseFloat(points[i].y)*1)+secondlatinc;