How do I store more information in a marker?
I'm using Google Maps v3 and I build in the server side a json collection of location data. So when I receive that, I iterate through that collection and create a marker object for each and every one of them.
For each of these markers, I bind them with the click event, so when the user clicks on a marker in the map, it displays an infoWindow with data related to the associated location.
I have an array to store all the location got from the server that holds the retrieved json objects and their corresponding marker.
The problem is that, even when I have an array that I can reference or iterate through, I need to not only get the marker object when the user clicks on them, but also the location object, that stores more information.
I tried to mantain this ar开发者_C百科ray of objects and reference it from the calling object without success, because the function is called by the marker and not the location object. So I thought if it's possible to store more information in the google maps marker object like using a general purpose field.
Please let me know if more information is needed.
Thanks!
Yes you can, thanks to JavaScript. In this language, objects and hashtables are the same thing1.
This is how you are creating your marker:
var point = new google.maps.LatLng(40.70, -74.00);
var myMarker = new google.maps.Marker({ position: point, map: map });
And this is how you can add an additional property to your myMarker
object:
myMarker.myNewField = 100;
Voila! No need to hold separate arrays of related data. No need of a general purpose field. Simply invent a new property name, and you're good to go.
1 A Survey of the JavaScript Programming Language by Douglas Crockford.
精彩评论