2
\$\begingroup\$

I was looking over questions related to setting up markers on a Google map, and though the following works perfectly fine for me, it was different from the other (and accepted) answers. I just wanted to see if I'm doing something incorrect, or just a different way.

Mine:

this references the marker, and you can pull any data you have associated with it simply by calling it within the loop that creates all of the markers.

google.maps.event.addListener(marker, "click", function(){
 infowindow.setContent(this.position.toString());
 infowindow.open(this.map, this);
});

Accepted:

 google.maps.event.addListener(marker, 'click', (function(marker, i) {
 return function() {
 infowindow.setContent(locations[i][0]);
 infowindow.open(map, marker);
 }
 })(marker, i));
RubberDuck
31.1k6 gold badges73 silver badges176 bronze badges
asked May 6, 2013 at 20:19
\$\endgroup\$
3
  • \$\begingroup\$ Your version does seem fine and simple. Can you give the link to the answers you saw? \$\endgroup\$ Commented May 7, 2013 at 7:48
  • \$\begingroup\$ Cool, good to know. And here is the link: stackoverflow.com/questions/3059044/… \$\endgroup\$ Commented May 8, 2013 at 16:44
  • \$\begingroup\$ I love how the answer goes : this is the simplest I could reduce it to ;) \$\endgroup\$ Commented Apr 1, 2014 at 1:00

1 Answer 1

3
\$\begingroup\$

Your code is definitely simpler, though I would not use it myself. There is no good reason to have an anonymous function, and if you have multiple markers, then you will have multiple clones of the same function. I would create a named function and use that function with addListener.

(I am assuming that infowindow is available to this function)

function setPositionAsContent(){
 infoWindow.setContent(this.position.toString());
 infoWindow.open(this.map, this);
}
google.maps.event.addListener(marker, "click", setPositionAsContent);
answered Apr 1, 2014 at 1:05
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.