Search code examples
javascriptgoogle-mapsgoogle-apipolylinegoogle-polyline

The infoWindow of each polyline in google maps is not shown using javascript


I try to display infoWindow for my polylines, In fact, I followed all steps of doing this task but still the infoWindow does not appear.. here I have several markers and I created path among them:

Javascript

 <style>
        #map
        {
            height:100%;
            width:100%;
        }
  </style>
  <script async defer
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBI1yC7eX6bOcbLruLZ224K5X4N-rwznjE&callback=initMap">
        </script>
        <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />

        <script>

            var markers = [

            //1 Qazvin Takestan   
            {
            "title": 'Qazvin',
            "lat": '36.2737',
            "lng": '49.9982',
            "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b>"
            }, 

            {
            "title": 'Takestan_dest',  
            "lat": '36.0721',
            "lng": '49.7013',
            "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان</b>"
            }, 


            //1 Qazvin Takestan kooh 36.066553, 49.638426
            {
            "title": 'Qazvin',
            "lat": '36.2737',
            "lng": '49.9982',
            "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b>"
            }, 

            {
            "title": 'Takestan Kooh_dest',  
            "lat": '36.066553',
            "lng": '49.638426',
            "description":"<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان کوه</b>"
            }, 


            //2 Takestan Razan 
            {
            "title": 'Takestan_src',  
            "lat": '36.0721',
            "lng": '49.7013',
            "description":"<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان</b>"
            },

            {
            "title": 'Razan',
            "lat": '35.3914',
            "lng": '49.0337',
            "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: رزن</b>"
            },


            //3 Takestan Abhar 
            {
            "title": 'Takestan_src',  
            "lat": '36.0721',
            "lng": '49.7013',
            "description":"<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان</b>"
            },

            {
            "title": 'Abhar', 
            "lat": '36.1525',
            "lng": '49.2385',
            "description":"<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: ابهر</b>"
            },

            //4 Abhar zanjan 36.1525° N, 49.2385° E
            {
            "title": 'Takestan_src',  
            "lat": '36.1525',
            "lng": '49.2385',
            "description":"<a href='edit-stations.php?temp_id=2018080250'><b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان</b></a>"
            },

            {
            "title": 'Zanjan', 
            "lat": '36.6830',
            "lng": '48.5087',
            "description":"<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: زنجان</b>"
            },

            //5 Qazvin Ziaran 36.1185° N, 50.5265    
            {
            "title": 'Qazvin',
            "lat": '36.2737',
            "lng": '49.9982',
            "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b>"
            }, 

            {
            "title": 'Ziaran',  
            "lat": '36.1185',
            "lng": '50.5265',
            "description":"<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: زیاران</b>"
            }, 

            //6 Ziaran karaj 35.8400° N, 50.9391° E   
            {
            "title": 'Ziaran',  
            "lat": '36.1185',
            "lng": '50.5265',
            "description":"<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: زیاران</b>"
            },  

            {
            "title": 'karaj',  
            "lat": '35.8400',
            "lng": '50.9391',
            "description":"<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: کرج</b>"
            },

            //7 Qazvin Loshan 36.6294° N, 49.5140° E  
            {
            "title": 'Qazvin',
            "lat": '36.2737',
            "lng": '49.9982',
            "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b>"
            },  

            {
            "title": 'Loshan',  
            "lat": '36.6294',
            "lng": '49.5140',
            "description":"<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: لوشان</b>"
            },

            //8 Qazvin BoeenZahra 35.7677° N, 50.0573° E 
            {
            "title": 'Qazvin',
            "lat": '36.2737',
            "lng": '49.9982',
           "description": "<a href='edit-stations.php?temp_id=2018082145'><b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b></a>"
            },  

            {
            "title": 'BoeenZahra',  
            "lat": '35.7677',
            "lng": '50.0573',
            "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: بویین زهرا</b>"
            }





];
        var infowindow2;
        var poly;
        var map;
        var marker;
        var path;
        var vertices;
        var polylines = []; 
        var flightPlanCoordinates;
        var zz = 0;   
        flightPlanCoordinates =[
           [
            {lat: 36.2737, lng: 49.9982},
            {lat: 35.7677, lng: 50.0573}
            ],
            [
            {lat: 36.2737, lng: 49.9982},
            {lat:36.543726,lng: 49.574846},
            {lat: 36.6294, lng: 49.5140}
            ]
        ];

        function initMap() {           
        var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.HYBRID 
        };

         // Define the symbol, using one of the predefined paths ('CIRCLE')
        // supplied by the Google Maps JavaScript API.
        var lineSymbol = {
          path: google.maps.SymbolPath.CIRCLE,
          scale: 8,
          strokeColor: '#393'
        };

        map = new google.maps.Map(document.getElementById("map"), mapOptions);
        var infoWindow = new google.maps.InfoWindow();

        //multi polylines
        var lat_lng = new Array();
        var latlngbounds = new google.maps.LatLngBounds();

        for (i = 0; i < markers.length; i++) {
        var data = markers[i];
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
        lat_lng.push(myLatlng);
        marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: data.title
        });
        latlngbounds.extend(marker.position);
        (function(marker, data) {
        google.maps.event.addListener(marker, "click", function(e) {
        infoWindow.setContent(data.description);
        infoWindow.open(map, marker);
        });
        })(marker, data);
        }

        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);

        //Initialize the Direction Service
        var service = new google.maps.DirectionsService();
         var hh =0;   
         //Loop and Draw Path Route between the Points on MAP
        for (var i = 0; i < lat_lng.length; i++) {

        if ((i + 1) < lat_lng.length) {
        var src = lat_lng[i];
        var des = lat_lng[i + 1];
        i = i+1;
        service.route({
        origin: src,
        destination: des,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
        }, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          //Initialize the Path Array
          path = new google.maps.MVCArray();



            //Set the Path Stroke Color
            poly = new google.maps.Polyline({
            //path: path,
            //path: flightPlanCoordinates[hh],
            icons: [{
            icon: lineSymbol,
            offset: '100%'
          }],
            map: map,
            //strokeColor: '#ec2a04'
            strokeWeight: 3.5,
            strokeColor: '#38ff45'
          });

        hh++;    

          poly.setPath(path);
          //poly.setPath(flightPlanCoordinates[0]);
          //poly.push(flightPlanCoordinates);

          polylines.push(poly);

          //polylines[0].setOptions({strokeColor: 'blue'}); 

          //var routeIndex = indexOfRequest(result);

          for (var i = 0, len = result.routes[0].overview_path.length ; i < len; i++) {
            path.push(result.routes[0].overview_path[i]);
          }

           animateCircle(poly);
        }
        });

        }
       //polylines[routeIndex].setPath(result.routes[0].overview_path);

        }
            createInfoWindow(poly, 'polyinfo...test'); //I tried polylines too
            google.maps.event.addDomListener(window, 'load', initialize);
        }

         function createInfoWindow(poly, content) {

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

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

        // Use the DOM setInterval() function to change the offset of the symbol
        // at fixed intervals.
        function animateCircle(line) {
          var count = 0;
          window.setInterval(function() {
            count = (count + 1) % 200;
            var icons = line.get('icons');
            icons[0].offset = (count / 2) + '%';
            line.set('icons', icons);
            }, 20);
        } 

    function changeRootProperty(pathID,pathStatus)
    {
        if((pathStatus%2) == 0)
            {
                polylines[pathID].setOptions({strokeColor: 'red'});
                document.getElementById("path"+pathID).innerHTML = "<span class='label label-danger'>غیرفعال</span>";
            }
        else
            {
                polylines[pathID].setOptions({strokeColor: '#38ff45'});
                document.getElementById("path"+pathID).innerHTML = "<span class='label label-success'>فعال</span>";
            } 
    } 

  </script>

index.html

<div id="map" style='width:100%;height:340px;'>

</div>

I tried many but still I have problem, when I click on markers, it's info window appears but for polylines does not.


Solution

  • With the posted code I get the javascript error: Uncaught TypeError: Cannot read property '__e3_' of undefined, because the DirectionsService is asynchronous and you are calling createInfoWindow(poly, 'polyinfo...test'); outside of its callback function (before the poly variable is created).

    You want to call that inside the callback function:

    function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          //Initialize the Path Array
          path = new google.maps.MVCArray();
          //Set the Path Stroke Color
          poly = new google.maps.Polyline({
            icons: [{
              icon: lineSymbol,
              offset: '100%'
            }],
            map: map,
            //strokeColor: '#ec2a04'
            strokeWeight: 3.5,
            strokeColor: '#38ff45'
          });
          hh++;
          poly.setPath(path);
          polylines.push(poly);
          for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
            path.push(result.routes[0].overview_path[i]);
          }
          animateCircle(poly);
          createInfoWindow(poly, 'polyinfo...test');  // <== call it inside the callback function
        }
      });
    

    Once I do that, I get a new error: Uncaught TypeError: Cannot read property 'setContent' of undefined because the variable infowindow2 is never initialize, add this to your initMap function:

    infowindow2 = new google.maps.InfoWindow();
    

    proof of concept fiddle

    screenshot of resulting map

    code snippet:

    var markers = [
    
      //1 Qazvin Takestan   
      {
        "title": 'Qazvin',
        "lat": '36.2737',
        "lng": '49.9982',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b>"
      },
    
      {
        "title": 'Takestan_dest',
        "lat": '36.0721',
        "lng": '49.7013',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان</b>"
      },
    
    
      //1 Qazvin Takestan kooh 36.066553, 49.638426
      {
        "title": 'Qazvin',
        "lat": '36.2737',
        "lng": '49.9982',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b>"
      },
    
      {
        "title": 'Takestan Kooh_dest',
        "lat": '36.066553',
        "lng": '49.638426',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان کوه</b>"
      },
    
    
      //2 Takestan Razan 
      {
        "title": 'Takestan_src',
        "lat": '36.0721',
        "lng": '49.7013',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان</b>"
      },
    
      {
        "title": 'Razan',
        "lat": '35.3914',
        "lng": '49.0337',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: رزن</b>"
      },
    
    
      //3 Takestan Abhar 
      {
        "title": 'Takestan_src',
        "lat": '36.0721',
        "lng": '49.7013',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان</b>"
      },
    
      {
        "title": 'Abhar',
        "lat": '36.1525',
        "lng": '49.2385',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: ابهر</b>"
      },
    
      //4 Abhar zanjan 36.1525° N, 49.2385° E
      {
        "title": 'Takestan_src',
        "lat": '36.1525',
        "lng": '49.2385',
        "description": "<a href='edit-stations.php?temp_id=2018080250'><b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: تاکستان</b></a>"
      },
    
      {
        "title": 'Zanjan',
        "lat": '36.6830',
        "lng": '48.5087',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: زنجان</b>"
      },
    
      //5 Qazvin Ziaran 36.1185° N, 50.5265    
      {
        "title": 'Qazvin',
        "lat": '36.2737',
        "lng": '49.9982',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b>"
      },
    
      {
        "title": 'Ziaran',
        "lat": '36.1185',
        "lng": '50.5265',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: زیاران</b>"
      },
    
      //6 Ziaran karaj 35.8400° N, 50.9391° E   
      {
        "title": 'Ziaran',
        "lat": '36.1185',
        "lng": '50.5265',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: زیاران</b>"
      },
    
      {
        "title": 'karaj',
        "lat": '35.8400',
        "lng": '50.9391',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: کرج</b>"
      },
    
      //7 Qazvin Loshan 36.6294° N, 49.5140° E  
      {
        "title": 'Qazvin',
        "lat": '36.2737',
        "lng": '49.9982',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b>"
      },
    
      {
        "title": 'Loshan',
        "lat": '36.6294',
        "lng": '49.5140',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: لوشان</b>"
      },
    
      //8 Qazvin BoeenZahra 35.7677° N, 50.0573° E 
      {
        "title": 'Qazvin',
        "lat": '36.2737',
        "lng": '49.9982',
        "description": "<a href='edit-stations.php?temp_id=2018082145'><b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: قزوین</b></a>"
      },
    
      {
        "title": 'BoeenZahra',
        "lat": '35.7677',
        "lng": '50.0573',
        "description": "<b style='padding-right:20px;font-family:tahoma;'>نام ایستگاه: بویین زهرا</b>"
      }
    ];
    var infowindow2;
    var poly;
    var map;
    var marker;
    var path;
    var vertices;
    var polylines = [];
    var flightPlanCoordinates;
    var zz = 0;
    flightPlanCoordinates = [
      [{
          lat: 36.2737,
          lng: 49.9982
        },
        {
          lat: 35.7677,
          lng: 50.0573
        }
      ],
      [{
          lat: 36.2737,
          lng: 49.9982
        },
        {
          lat: 36.543726,
          lng: 49.574846
        },
        {
          lat: 36.6294,
          lng: 49.5140
        }
      ]
    ];
    
    function initMap() {
      var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.HYBRID
      };
    
      // Define the symbol, using one of the predefined paths ('CIRCLE')
      // supplied by the Google Maps JavaScript API.
      var lineSymbol = {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 8,
        strokeColor: '#393'
      };
    
      map = new google.maps.Map(document.getElementById("map"), mapOptions);
      var infoWindow = new google.maps.InfoWindow();
      infowindow2 = new google.maps.InfoWindow();
    
      //multi polylines
      var lat_lng = new Array();
      var latlngbounds = new google.maps.LatLngBounds();
    
      for (i = 0; i < markers.length; i++) {
        var data = markers[i];
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
        lat_lng.push(myLatlng);
        marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: data.title
        });
        latlngbounds.extend(marker.position);
        (function(marker, data) {
          google.maps.event.addListener(marker, "click", function(e) {
            infoWindow.setContent(data.description);
            infoWindow.open(map, marker);
          });
        })(marker, data);
      }
    
      map.setCenter(latlngbounds.getCenter());
      map.fitBounds(latlngbounds);
    
      //Initialize the Direction Service
      var service = new google.maps.DirectionsService();
      var hh = 0;
      //Loop and Draw Path Route between the Points on MAP
      for (var i = 0; i < lat_lng.length; i++) {
    
        if ((i + 1) < lat_lng.length) {
          var src = lat_lng[i];
          var des = lat_lng[i + 1];
          i = i + 1;
          service.route({
            origin: src,
            destination: des,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
          }, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
              //Initialize the Path Array
              path = new google.maps.MVCArray();
              //Set the Path Stroke Color
              poly = new google.maps.Polyline({
                icons: [{
                  icon: lineSymbol,
                  offset: '100%'
                }],
                map: map,
                strokeWeight: 3.5,
                strokeColor: '#38ff45'
              });
              hh++;
              poly.setPath(path);
              polylines.push(poly);
              for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                path.push(result.routes[0].overview_path[i]);
              }
    
              animateCircle(poly);
              createInfoWindow(poly, 'polyinfo...test');
            }
          });
        }
      }
    }
    google.maps.event.addDomListener(window, 'load', initMap);
    
    function createInfoWindow(poly, content) {
      google.maps.event.addListener(poly, 'click', function(event) {
        infowindow2.setContent(content);
        infowindow2.setPosition(event.latLng);
        infowindow2.open(map);
      });
    }
    
    // Use the DOM setInterval() function to change the offset of the symbol
    // at fixed intervals.
    function animateCircle(line) {
      var count = 0;
      window.setInterval(function() {
        count = (count + 1) % 200;
        var icons = line.get('icons');
        icons[0].offset = (count / 2) + '%';
        line.set('icons', icons);
      }, 20);
    }
    
    function changeRootProperty(pathID, pathStatus) {
      if ((pathStatus % 2) == 0) {
        polylines[pathID].setOptions({
          strokeColor: 'red'
        });
        document.getElementById("path" + pathID).innerHTML = "<span class='label label-danger'>غیرفعال</span>";
      } else {
        polylines[pathID].setOptions({
          strokeColor: '#38ff45'
        });
        document.getElementById("path" + pathID).innerHTML = "<span class='label label-success'>فعال</span>";
      }
    }
    html,
    body,
    #map {
      height: 100%;
      width: 100%;
      padding: 0px;
      margin: 0px;
      background-color: white;
    }
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <div id='map'></div>