Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

130 Part II — Instant Gratification


This application is incredibly useful. In fact, it was invaluable to me when preparing this chapter
because it provided the information needed for the examples.

As an extension of that principle, a minor change to the function called by the listener shows
each point clicked, and also draws the polyline that would be created with each click. Listing
7-13 shows the updated code for the application. This system is also useful for building routes,
boxes, and other shapes.

Listing 7-13: Dynamically Building Polylines while Getting Location Data

var map;
var points = [];
var route;

function onLoad() {
if (GBrowserIsCompatible()) {
map = new GMap(document.getElementById(“map”));

GEvent.addListener(map, ‘click’, function(overlay,point) {
var latLngStr = ‘(‘ + point.x + ‘, ‘ + point.y + ‘)<br/>’;
var message = document.getElementById(“message”);
message.innerHTML = message.innerHTML + latLngStr;
if (route) {
map.removeOverlay(route);
}
points.push(point);
if (points.length > 1) {
route = new GPolyline(points);
map.addOverlay(route);
}
});

map.centerAndZoom(new GPoint(-0.64,52.909444), 2);
}
}

The application works by creating a global array to hold each point, and a variable to hold the
polyline that is generated each time.

Each time the user clicks on the map, the application adds a point to the array. If the length of
the array of points is greater than one, there is enough information to build a polyline. If the
polyline is created, it is recorded and the overlay is deleted and redrawn with each click. So that
a record of each point clicked is included, the message displayed at the bottom of the map is
also updated with each point.
Free download pdf