Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

112 Part II — Instant Gratification


In short, to add a marker:

1.Create a GPoint().
2.Create a new GMarkerusing the GPoint.

3.Add the GMarkerto the map using addOverlay().

The movemap()function from the previous example can be adjusted so that it adds a marker
to the map when a restaurant is clicked. Listing 7-4 shows an updated movemap()function
with the added steps, and Figure 7-5 shows the results.

Listing 7-4:Adding a Marker to the Map Movement Function

var marker;

function movemap(x,y) {
if (marker)
{
map.removeOverlay(marker);
}
var point = new GPoint(parseFloat(x),parseFloat(y));
map.recenterOrPanToLatLng(point);
marker = new GMarker(point);
map.addOverlay(marker);
}

For convenience, the marker object is created globally, and the existing marker is removed before
moving the map and creating the new marker for the selected restaurant. This latter operation is
handled by checking whether the marker variable has already been configured. If it has, you can
remove it from the map by calling the removeOverlay()method. Because the object holding
the marker is created globally, you can easily call it from the method to remove it.

Adding Multiple Markers


Highlighting one location, as in the previous example, is useful, but it’s not really very handy if
you want to show users all of the potential restaurants or locations that are available on a map.
In the restaurant example, what would be really useful is to show the location of a number of
potential restaurants that the user might be interested in.

If you don’t actually want to keep or update the markers, the movemap()can be further sim-
plified to create a marker each time the user clicks a restaurant. Listing 7-5 shows an altered
movemap().
Free download pdf