-2

I have built a web app using Google maps Api and get a problem with polyline clicked event. I tried to add some markers to maps, then joined them together. I expect that if I click on polyline, I can get markers that are start point and end point of that polyline. However, only one result returned same same for all times I click the different polylines.Here my source code:

var locations = [
    { title: "Site 1", lat: 16.044137, lng: 108.206511 },
    { title: "Site 2", lat: 16.067161, lng: 108.186259 },
    { title: "Site 3", lat: 16.063472, lng: 108.215248 },
    { title: "Site 4", lat: 16.041847, lng: 108.193539 },
    { title: "Site 5", lat: 16.054186, lng: 108.172890 },
];

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 14,
    center: new google.maps.LatLng(16.067161, 108.186259),
    mapTypeId: google.maps.MapTypeId.SATELLITE
});

var infowindow = new google.maps.InfoWindow();

var polyLineClicked = function (polyline, fromIndex, toIndex) {
    google.maps.event.addListener(polyline, 'click', function (e) {
        infowindow.setContent = fromIndex + " to " + toIndex;
        infowindow.setPosition = event.latLng;
        infowindow.open(map);
    });
}
for (var i = 0; i < locations.length; i++) {
    var position = new google.maps.LatLng(locations[i].lat, locations[i].lng);
   var marker = new google.maps.Marker({
        position: position,
        map: map
    });

    google.maps.event.addListener(marker, 'click', (function (marker, i) {
        return function () {
            infowindow.setContent(locations[i].title);
            infowindow.open(map, marker);
        }
    })(marker, i));

    if (i <= locations.length - 2) {

        var nextPosition = new google.maps.LatLng(locations[i + 1].lat, locations[i + 1].lng);
        var polyline = new google.maps.Polyline({
            path: [position, nextPosition],
            strokeColor: 'black',
            strokeOpacity: 1,
            strokeWeight: 7,
            map: map,
            fromPositionIndex: i,
            toPositionIndex: i+1
        });
        var fromIndex = locations[i].title;
        var toIndex = locations[i + 1].title;

        polyLineClicked(polyline, fromIndex, toIndex);
    }
}
geocodezip
  • 158,664
  • 13
  • 220
  • 245
Rim Vo
  • 22
  • 2

1 Answers1

2

In your polyLineClicked function, you are reassigning setContent and setPosition rather than calling the infoWindow class methods.

var polyLineClicked = function(polyline, fromIndex, toIndex) {
  google.maps.event.addListener(polyline, 'click', function(e) {
    // call the methods instead of reassigning
    infowindow.setContent(fromIndex + " to " + toIndex);
    infowindow.setPosition(e.latLng);
    infowindow.open(map);
  });
};

jsfiddle

Thomas
  • 96
  • 5