3

I want to display an alert with the marker info when I click on it. I receive the parameters as a json and my problem is when I click any marker, it is always displaying the info of the last marker. I don´t know where the problem can be.

 var map = new google.maps.Map(document.getElementById('map'),
                        mapOptions);

                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function (position) {
                        var userPos = new google.maps.LatLng(position.coords.latitude,
                                position.coords.longitude)
                        var markUsr = new google.maps.Marker({
                            position: userPos,
                            map: map,
                            icon: 'images/locblue.png'
                        });

                        map.setCenter(markUsr.position);
                        for (var i = 0; i < data.length; i++) {
                            var pos = new google.maps.LatLng(data[i].latitud, data[i].longitud)

                            var marker = new google.maps.Marker({
                                position: pos,
                                map: map,
                                icon: 'images/locred.png',
                                description: data[i].desc
                            });

                            var infowindow = new google.maps.InfoWindow({
                                content: data[i].name
                            });

                            infowindow.open(map, marker)
                            google.maps.event.addListener(marker, 'click', function () {
                                alert(marker.description)
                            })
                        }
                    })
                }

2 Answers 2

8

I had almost the exact same problem with Google Maps. As far as I understand (which would explain the problem and solution), when you click a marker, JS essentially goes back to the scope of wherever google.maps.event.addListener is called. However, it doesn't store n (data.length) different marker variables. It just remembers the last one.

To solve this, create a list of markers before the for loop, and reference indices in the list instead of just one marker variable. Store the index of each marker in an id property to keep it available. Like this:

...

map.setCenter(markUsr.position);
var markers = [];
for (var i = 0; i < data.length; i++) {
    var pos = new google.maps.LatLng(data[i].latitud, data[i].longitud);

    markers[i] = new google.maps.Marker({
        position: pos,
        map: map,
        icon: 'images/locred.png',
        description: data[i].desc,
        id: i
    });

    var infowindow = new google.maps.InfoWindow({
        content: data[i].name
    });

    infowindow.open(map, markers[i]);
    google.maps.event.addListener(markers[i], 'click', function () {
        alert(markers[this.id].description)
    })
}

...

Sometimes JS can be very unintuitive, but this is how I solved it.

As a side note, you were missing a couple of semicolons.

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

2 Comments

it does not show anything, with your answer I think the problem is in the alert line with the variable i. Correct me if I am wrong
Edited. See if it works when storing the index of each marker in its id.
1

JS allowed me to do this in a forEach. Every time I tried to break the marker function out onto its own, I would get 0 results on the map. Somehow this magically works where having the marker function in it's own function and calling it via for loop doesn't work. I really don't know what but thought I would share another solution. This plotted over 200 points on the same map for me :)

dataSet.forEach((item, index) => {
    coords = {lat:item[2], lng:item[3]}
    if(item[1] > 500){
        color = 'red';
        var marker = new google.maps.Marker({
                position: coords,
                map:map,
                icon: {
                url: `http://maps.google.com/mapfiles/ms/icons/${color}-dot.png`
                }
            });
    }
    else if((item[1] < 500) && (item[1] > 100)){
        color = 'pink';
        var marker = new google.maps.Marker({
                position: coords,
                map:map,
                icon: {
                url: `http://maps.google.com/mapfiles/ms/icons/${color}-dot.png`
                }
            });
    }
    else{
        color = 'blue';
        var marker = new google.maps.Marker({
                position: coords,
                map:map,
                icon: {
                url: `http://maps.google.com/mapfiles/ms/icons/${color}-dot.png`
                }
            });
    }
})

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.