Friday, January 12, 2007

Dirty hack to get google map working for me

My requirement was to show addressing details plus some additional details when a user click on a marker in google map. The additional detail I set, always got reset to the last user data in my array. Investigating the cause, I found that, google map API does not call addAddressToMap callback function (code shown below) each time when I iterate through the loop. Rather, it calls these callback functions at the end. So, I decided to use a global variable to hold additional details. Having fixed that, I ran into another problem. I had to declare a local variable to copy the global value and then add a listener to each marker object. Here's the complete javascript source.

var map;
var geocoder;
var detail;
var marker;
var counter = 0;
var details = new Array()
var locations = new Array()

//------------------------------------------------------------
//user information
//you can populate these arrays using an xml file for example
details[0] = 'Mohamed Nabeel
CS Graduate Student (2006)';

locations[0] = 'Galle, Sri Lanka';
details[1] = 'Farrukh Mateen
ME MS Student (2006)';

locations[1] = 'Islamabad, Pakistan';
var headcount = 2;
//------------------------------------------------------------

function addAddressToMap(response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode that address");
} else {
var place = response.Placemark[0];
var detailx;
var point = new GLatLng(place.Point.coordinates[1],
place.Point.coordinates[0]);
var marker = new GMarker(point);
detailx = details[counter++];

GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(detailx + '
' + place.address);});

map.addOverlay(marker);
}
}

// showLocation() is called when you click on the Search button
// in the form. It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation(address) {
geocoder.getLocations(address, addAddressToMap);
}

function load() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(0,0), 1);
geocoder = new GClientGeocoder();
var i = 0;
for(;i
showLocation(locations[i]);
}
}
}

No comments: