Question

I have a map with multiple polylines and would like to open a line-specific-infowindow when clicking the line.

So far my code can't shown any infowindow when click the line, Here is my code:

 var poly;
        var polyOptions = {
          strokeColor: '#ff0000',    
          strokeOpacity: 1.0,   
          strokeWeight: 3    
        }
        poly = new google.maps.Polyline(polyOptions);
        poly.setMap(map);   

        for(var i=0; i<locations.length; i++){
            var loc = locations[i].split(',');
            var path = poly.getPath();    
            path.push(new google.maps.LatLng(loc[0], loc[1]));    
            createInfoWindow(poly,'polyinfo...test');
        }


        function createInfoWindow(poly,content) {
          google.maps.event.addListener(poly, 'click', function(event) {
          infowindow.content = content;
          infowindow.position = event.latLng;
          infowindow.open(map);
         });
        }
Was it helpful?

Solution

There is no need to call poly.getPath() and createInfoWindow(poly, 'polyinfo...test'); for each point. It could be called only once before and when the whole path is created:

var path = poly.getPath();

for (var i = 0; i < locations.length; i++) {
    //var loc = locations[i].split(',');
    var loc = locations[i];
    path.push(new google.maps.LatLng(loc[0], loc[1]));
    //createInfoWindow(poly, 'polyinfo...test');
}

createInfoWindow(poly, 'polyinfo...test');

To set content and position of infowindow you have to use methods for that:

function createInfoWindow(poly, content) {

    google.maps.event.addListener(poly, 'click', function(event) {
        // infowindow.content = content;
        infowindow.setContent(content);

        // infowindow.position = event.latLng;
        infowindow.setPosition(event.latLng);
        infowindow.open(map);
    });
}

See whole example at jsbin.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top