Search code examples
google-mapsgoogle-maps-api-3onclickpolylinegoogle-polyline

Incorrect Polyline Click fired when having multiple Polylines on Map


I have multiple polylines on a Google Map and add a 'click' event handler for each. All these polylines are added via javascript code. However when I click on any polyline on map, the click event for the last added polyline is fired. This makes it difficult to identify the line clicked.

The code that creates the Polylines is:

    $.ajax({
                type: "GET",
                url: "MapData.html",
                success: function (json) {
                    mapData = JSON.parse(json);
                    var newroad;
                    for (var i = 0; i < mapData.length; i++) {
                        newroad = new google.maps.Polyline({
                            ID: mapData[i].ID,
                            path: google.maps.geometry.encoding.decodePath(mapData[i].latLngs),
                            strokeColor: 'blue',
                            strokeOpacity: 0.75,
                            strokeWeight: 3
                        });

                        newroad.setMap(map);
                        google.maps.event.addListener(newroad, 'click', function () {

                            setSelectedRoad(newroad);
                        });
                    }
                },
                error: function () {
                    alert('Critical Data Failure');
                }
            });

The data is correctly fetched from the server and all polylines are displayed in blue as expected. The function that gets called when a polyline is clicked is

    function setSelectedRoad(road) {
        road.strokeColor = 'black';
        road.setOptions({ strokeColor: 'black', strokeOpacity: 1.0 });
        selectedRoadID = road.ID;
    }

However the "selectedRoadID" always turns out to be the last polyline added and the color for that line changes to black, even if any other polyline is clicked.

The confusing part is that if I draw a fresh polyline on the map and set its click event to the same function, then that works properly. I do get proper ID for the polyline clicked. This works for any number of new lines drawn and works properly for clicking them in any order.


Solution

  • I found that changing

        newroad.setMap(map);
        google.maps.event.addListener(newroad, 'click', function () {
    
               setSelectedRoad(newroad);
        });
    

    to

        newroad.setMap(map);
        google.maps.event.addListener(newroad, 'click', function () {
    
               setSelectedRoad(this);
        });
    

    fixed everything.