i have several markers (in array) on map, each custom id tag i've given them.
what want: when click on marker, wish add it's id array.
the problem: mouse event google not have target attribute, position, can't seem access id directly.
i don't want have resort using position find closest marker , returning it's id way, it's rather convoluted.
all appreciated
this easy, feature in javascript , many other languages called closure.
simply put code creates marker , sets event listener(s) insidea function, , call function each marker data needed specific marker. example:
var places = [ { id: 'one', lat: 1, lng: -1, name: 'first' }, { id: 'two', lat: 2, lng: -2, name: 'second' } ]; for( var = 0; < places.length; i++ ) { addplace( places[i] ); } function addplace( place ) { var marker = new google.maps.marker({ map: map, position: new google.maps.latlng( place.lat, place.lng ), title: place.name }); google.maps.event.addlistener( 'click', function() { alert( 'clicked ' + place.id + ': ' + place.name ); }); }
i didn't test maps api code, specifics of code not important. important understand place
variable see used in code. key part: variable accessible inside event listener, because event listener nested inside addplace()
function has place
parameter.
note difference between code , code this, not work:
for( var = 0; < places.length; i++ ) { var place = places[i]; var marker = new google.maps.marker({ map: map, position: new google.maps.latlng( place.lat, place.lng ), title: place.name }); google.maps.event.addlistener( 'click', function() { alert( 'clicked ' + place.id + ': ' + place.name ); }); }
the difference between 2 working version puts loop body in separate function called loop, instead of having code directly inside loop. having code in function call each time creates closure, , that's lets inner event listener function "see" variables in outer function.
the great thing closures can use them in any similar situation. isn't specific maps api or objects api uses. may have used them , not realized it, example in settimeout()
call this:
// display alert 'time' milliseconds after function called function slowalert( message, time ) { settimeout( function() { alert( message ); }, time ); } slowalert( 'howdy!', 1000 ); // wait second , howdy!
where alert()
call made inside settimeout()
callback function made, it's using closure on slowalert()
function pick value of message
variable passed function.
Comments
Post a Comment