I've been playing with the Google Maps tag supplied with RichFaces this week and it's been a bit frustrating regarding the lack of documentation for getting markers to function. While I haven't actually finialised the routines on the project, I thought I'd share my knowledge and hopefully you'll find it of some use.

First up, let's consider the composition of the tag:


<rich:gmap
mapType="G_NORMAL_MAP"
lat="#{address.latitude}"
lng="#{address.longitude}"
zoom="5"
gmapVar="map"
gmapKey="your gmap API key"
oninit="init(map)"
id="map"/>


OK, in order


  • mapType is the type of map you can display: here we're going for a normal map: no satellite images or hybrids - possible values are G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP.

  • lat is the starting latitude of the map with the value in the range of -90 to +90

  • lng is the starting longitude of the map with the value in the range of -180 to +180

  • zoom is the zoom ratio of the map 1 being furthest out and 18 being the closest

  • gmapVar is the name of the object created in the DOM on the browser for your map

  • gmapKey is the Google maps API key you'll need to access Google maps

  • oninit is a JavaScript method your map needs to call on start up - we'll get to this in a minute as it's very important

  • id is the id of this element in the browser - this is distinct from gmapVar



So this will display a map for you that will start at your lat / lng position and allow you to move around and zoom in and out. But beyond that, it won't let you do anything really useful. What I needed was the ability to add markers to the map for the project I'm working on and this is all handled in the 'init(map)' call.

This JavaScript method is used to add event listeners to the map that respond to events on the map. Read the Google docs if you want more info on what can be captured as an event. At the moment, I'm only interested in the user clicking on the map, so here is my listener.


var marker_count = 0;
var lat;
var lng;

function init(map) {
GEvent.addListener(map, "click", function(marker, point) {
if(marker) {
// a marker has been clicked; remove it
marker_count = marker_count-1;
map.removeOverlay(marker);
} else {
// add a marker
marker = new GMarker(point);
map.addOverlay(marker);
}
});
}


And that's a working map. From your GMarker, you can get the GLatLng object that will allow you to retrieve the latitude and longitude of the marker for later. I store these values in hidden form elements that are mapped into my backing Address bean.

As I progress with this work, I'm going to be adding geolocation look-ups (mainly focussed around UK postcodes initially) so keep checking back for more!