Tuesday, August 25, 2009

JavaScript Insight With Google Map API

I have a couple hundred markers I want to add to a Google Map via the Google Map API. For each one I want to have a clickable Info Window with a little bit of HTML in the window. The Google Map API function written in JavaScript to do this is:
GEvent.addListener(marker , ‘click’, function() { … } );
The first parameter is the marker instance, the second is the event, and the last parameter is the function to execute when the click event takes place on the marker. However, notice that there isn’t any place to send in parameters. addListener doesn’t have an optional parameters property, and the method doesn’t allow you to create a function that takes parameters – since it wouldn’t know what to pass there. Which leaves me with the problem: how do I pass in the HTML that I want to display on the click? I could create a global array of html data that I fill and reference that global from inside the function, however this is messy. The answer is to tell the marker what the HTML is and then extract it from the marker. However, the marker is of type GMarker which is a Google class. If this was C# I would have to subclass the GMarker object and add another property. However, subclassing (or the equivalent) is way too complicated in JavaScript. The solution is to understand that you can just add a property to an instance of the Javascript object without having to declare the property in the object. In fact you can just tag on the HTML data and get it later – even though if it is someone else’s object. So my code looks like this:
var marker = new GMarker(point);
marker.html = ‘<b>’ + title + ‘</b>’;
GEvent.addListener(marker, ‘click’, function() { this.openInfoWindowHtml(this.html)});
In the function, this refers to the instance of the object which the action was taken, which in this case is the marker. So this.html has the information for this marker’s html, which is displayed in the Info window. {6230289B-5BEE-409e-932A-2F01FA407A92}

No comments:

Post a Comment