0

I'm having difficulty setting event handlers to Google Maps markers in JavaScript. Below is my code:

var map = new google.maps.Map(document.getElementById('map-canvas'), {
                zoom: 8,
                center: {lat: -35, lng: 149}
            });
            for (var i = 0; i < basketballCourts.length; i++) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(basketballCourts[i].latitude, basketballCourts[i].longitude),
                    map: map,
                    title: 'Hello World!'
                });
                marker.set("data-index", i);
                google.maps.event.addListener(marker, 'click', function() {
                    console.log(marker.get("data-index"));
                });
            }

You'll notice that there is a click event for the markers. However, the click event is the same for all the markers. A different number should be logged for every marker click, but no matter what marker I click on, I get the same response.

I'm not sure how to fix this.

1
  • 3
    Try this.get("data-index") to see if you can use this to get the correct marker. Commented Jul 3, 2015 at 20:03

1 Answer 1

2

What's happening is you're looping over all your basketballCourts, creating an event listener for each marker. That's all well and good. However that event listener function looks like:

console.log(marker.get("data-index"));

The function executes in response to a marker click, not when you define it. And the value of marker when the function executes will be the value it had at the end of your loop over all the basketballCourts.

Using @MiltoxBeyond's suggestion, try using this.get("data-index")

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.