That would create an anonymous function for each marker as well, so no
saving in terms of function counts. To actually share the function, do
function createMarker(latlon,markerId){
var marker = new google.maps.Marker({
marker.myMarkerId - markerId;
google.maps.event.addListener(marker, 'click', markerClick);
return marker;
}
function markerClick(e){
var mk = this;
alert(mk.myMarkerId);
// do stuff with mk
}
Just need to be careful when inside markerClick, "this" is actually
the marker.
On Jul 26, 3:17 am, Marcelo <[email protected]> wrote:
> It's probably not too heavy and it is common practice, but if you
> prefer it you can use a single named function, like:
>
> function createMarker(latlon,markerId) {
> var marker = new google.maps.Marker({position: latlon, ... etc.
> marker.myMarkerId = markerId;
> google.maps.event.addListener(marker, 'click', function()
> {markerClick(this)});
> return marker;
>
> }
>
> function markerClick (clickedMarker) {
> var markerId = clickedMarker.myMarkerId;
> // Do something with markerId
>
> }
>
> In the scope of the event handler function the marker itself is the
> variable 'this'.
> That's similar to the map event handlers
> here:http://maps.forum.nu/gm_maps_in_sync.html
> Note that one single function handles events of the same type for all
> maps.
>
> --
> Marcelo -http://maps.forum.nu
> --
>
> On Jul 26, 8:25 am, zinigor <[email protected]> wrote:
>
> > Hello! I am using Google Maps V3, and I have the following question.
>
> > I understand that if I have multiple markers on a map, and I need to
> > handle clicks on them, I have to set up a handler for each marker like
> > so:
>
> > // ...
> > var marker = new google.maps.Marker({position: new
> > google.maps.LatLng(55, 37)});
> > marker.setMap(map);
> > var listener = google.maps.event.addListener(marker, 'click',
> > function(event){
> > // my listener handler here
>
> > });
>
> > But if I have a lot of markers, wouldn't it bee too heavy? Can I
> > somehow set one handler and figure out which marker was clicked inside
> > it? Like:
>
> > // ...
> > var listener = google.maps.event.addListener(map, 'click',
> > function(event){
> > var target = event.target; // Click target
>
> > });
--
You received this message because you are subscribed to the Google Groups
"Google Maps JavaScript API v3" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/google-maps-js-api-v3?hl=en.