Search code examples
google-mapsgoogle-maps-api-3infowindow

info-window for multiple dynamic locations on google map is not showing properly


Google map info-window is not showing the details properly when the new locations array is updated.

refer: call function1 and click the marker, there you can see the info-window details. but when i try function2 after function1, the info-window shows undefined.. see the image here for reference

note: this is just a sample file with same functionality as my original file.

    var locations=[];
    var markersinfo=[];
    var gmarkers=[];

//all events function
    function allevents() {
        $('#checkinstatus').val('');
        
                    for(i=0; i<gmarkers.length; i++){
                        gmarkers[i].setMap(null);
                    }

                        locations=[];
                        markersinfo=[];

            var parseddata=[
                {            
                    "Start_DateTime": "2018-08-06T19:00:00+10:00",           
                    "Event_Title": "testing event creation 5",
                    "End_DateTime": "2018-08-06T19:30:00+10:00",           
                    "dateforfilter": "2018-08-26",
                    "Check_In_Status": "PLANNED",
                    "Venue": "1 Street Name City NSW 0000 Australia",            
                },
                {            
                    "Start_DateTime": "2018-08-06T17:00:00+10:00",            
                    "Event_Title": "testing event creation 6",
                    "End_DateTime": "2018-08-06T17:30:00+10:00",            
                    "dateforfilter": "2018-08-26",
                    "Check_In_Status": "PLANNED",
                    "Venue": "3111  Sampson Street Aurora Colorado 80014 US",
                }
            ];

                        var allevents=parseddata;
                        for (i = 0; i < allevents.length; i++) {
                                                        
                                var locobj=allevents[i].Venue; 
                                var markersobj=['<div class="info_content">' + '<h3>'+allevents[i].Event_Title +'</h3>' + '<p>CheckIn-Status:'+ allevents[i].Check_In_Status +'</p>' + '</div>'];
                                
                                if(locobj == null ){
                                    
                                }
                                else{
                                    markersinfo.push(markersobj);
                                    locations.push(locobj);
                                }
                                
                        }
                        rungooglemap();
    };

//CheckedIn-Status based filters
    function getcheckinlocationfilter()
    {   

        
        var x = document.getElementById("checkinstatus").value;
        //console.log('checkinstatus filter', x);
        if(x == 'VISITED')
        {
                    for(i=0; i<gmarkers.length; i++){
                        gmarkers[i].setMap(null);
                    }
 
            var parseddata=[
                {            
                    "Start_DateTime": "2018-08-06T19:00:00+10:00",           
                    "Event_Title": "testing event creation 3",
                    "End_DateTime": "2018-08-06T19:30:00+10:00",           
                    "dateforfilter": "2018-08-26",
                    "Check_In_Status": "PLANNED",
                    "Venue": "2851 Jacobs Street Coraopolis PA Pennsylvania 15108",            
                },
                {            
                    "Start_DateTime": "2018-08-06T17:00:00+10:00",            
                    "Event_Title": "testing event creation 4",
                    "End_DateTime": "2018-08-06T17:30:00+10:00",            
                    "dateforfilter": "2018-08-26",
                    "Check_In_Status": "PLANNED",
                    "Venue": "mysuru museum karnataka",
                },
                {            
                    "Start_DateTime": "2018-08-06T19:00:00+10:00",           
                    "Event_Title": "testing event creation 3",
                    "End_DateTime": "2018-08-06T19:30:00+10:00",           
                    "dateforfilter": "2018-08-26",
                    "Check_In_Status": "PLANNED",
                    "Venue": "5 Carter St South Melbourne",            
                },
                {            
                    "Start_DateTime": "2018-08-06T17:00:00+10:00",            
                    "Event_Title": "testing event creation 4",
                    "End_DateTime": "2018-08-06T17:30:00+10:00",            
                    "dateforfilter": "2018-08-26",
                    "Check_In_Status": "PLANNED",
                    "Venue": "Adyar Ananda Bhavan, 7, Mahatma Gandhi Road, Shastri Nagar, Adyar, Chennai, Tamil Nadu 600020",
                },

            ];    
                        var checkedinevents=parseddata;

                            locations=[];
                            markersinfo=[];

                            for(i = 0; i < checkedinevents.length; i++)
                            {
                                var locobj=checkedinevents[i].Venue; 
                                console.log(locobj);
                                var markersobj=['<div class="info_content">' + '<h3>'+checkedinevents[i].Event_Title + '</h3>' + '<p>From : ' + checkedinevents[i].Start_DateTime + '</p>' + '<p>To :'+ checkedinevents[i].End_DateTime +'</p>' + '</div>'];
                                
                                if(locobj == null ){
                                    //console.log('There is no address in the event');
                                }
                                else{
                                   // console.log('not a null',locobj);
                                        markersinfo.push(markersobj);
                                        locations.push(locobj);
                                }
                            }

                            
                        rungooglemap();
                   
                }
        else if(x == 'PLANNED')
        {
           // console.log('PLANNED');
        }
        else
        {
            //console.log('select option');
        }      
    }


//google map part starts here
        var nextAddress = 0;
        var infovalue = 0;
        var delay = 100;
        var infowindow = new google.maps.InfoWindow();
        var latlng = new google.maps.LatLng(21.0000, 78.0000);
        var mapOptions = {
            zoom: 5,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            //gestureHandling: 'greedy',
        }
        var geocoder = new google.maps.Geocoder();
        var map      = new google.maps.Map(document.getElementById("map"), mapOptions);
        var bounds   = new google.maps.LatLngBounds();
        

    //geocoding address conversion function
        function geocodeAddress(address, next) {
            geocoder.geocode({
                address: address
            }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var p = results[0].geometry.location;
                    var lat = p.lat();
                    var lng = p.lng();
                    createMarker(infovalue, lat, lng);
                    infovalue++;   
                } else {
                    if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                        nextAddress--;
                        delay++;
                    } else {}
                }
                next();
            });
        }

    //markers creation and info window data handling
        function createMarker(add, lat, lng) {
            var image='gps2.png';
    
            var contentString = add;
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(lat, lng),
                map: map,
                //icon: new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"),
            });
            
            //clear the previous locations
            gmarkers.push(marker);

            //Create and open InfoWindow.
            var infoWindow = new google.maps.InfoWindow();

            google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent("<div style = 'width:200px;min-height:40px'>" + markersinfo[add] + "</div>");
                infowindow.open(map, marker);
            });  

            bounds.extend(marker.position);
        }

    //based on the address count calling a geocoding function one by one 
        function theNext() {
            if (nextAddress < locations.length) {
                setTimeout('geocodeAddress("' + locations[nextAddress] + '",theNext)', delay);
                nextAddress++;           
            } else {
                map.fitBounds(bounds);
            }
        }

    //forwarding from individual functions to google api
    function rungooglemap(value) {
        for(i=0; i<gmarkers.length; i++){
            gmarkers[i].setMap(null);
        }
            nextAddress = 0;		
            theNext();           
    }
    html {height: 100%}    
    body {height: 100%;margin: 0;padding: 0}    
    #map {width: 100%;height: 100%;}
    .button {border-radius: 4px;background-color: #f4511e;border: none;color: #FFFFFF;text-align: center; font-size: 28px;          padding: 20px;width: 200px;transition: all 0.5s;cursor: pointer;margin: 5px;}
    .button span {cursor: pointer;display: inline-block;position: relative;transition: 0.5s;}
    .button span:after {content: '\00bb';position: absolute;opacity: 0;top: 0;right: -20px;transition: 0.5s;}
    .button:hover span {padding-right: 25px;}
    .button:hover span:after {opacity: 1;right: 0;}
    select{
	background-color: #f9fbfb;
	border:1px solid #c6cbd4;
	border-radius:4px;
	height: 40px;
	margin-top: 5px;
	margin-bottom: 20px;
	padding: 8px;
	font-size: 14px;
	outline: none;
	width: 100%;

	-webkit-appearance: none;
	appearance: none;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Account Locations</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyB3pwJBXen9pU6syjpqZHQvoeZOEYoPWsM">
    </script>
</head>

<body>
    
    <div style="float:left;width:100%;margin-bottom:0px;margin-top:15px;">

        <div style="float:left;width:50%;text-align:center;">
            <button class="button" style="height:80px;" name="allevents" onclick="allevents()" value="allevents"><span style="margin-top: -12px;"> function 1</span></button>
        </div>

        <div style="float:left;width:50%;text-align:center;">           
            <h1 style="margin-top: 0px;height:10px;color: #f4511e;">function 1</h1>   
            <select name="checkinstatus" id="checkinstatus" onchange="getcheckinlocationfilter()" style="border-color: coral;border-bottom-width: 5px;width: 60%;">
            <option value="Select any one option"> Select any one option </option>
            <option value="VISITED"> visited </option>
            <!-- <option value="PLANNED"> planned </option>  -->
            </select>
        </div>
        
    </div>

    <!-- google map div-->       
    <div id="map" ></div>

</body>


</html>


Solution

  • You aren't setting the infovalue variable back to 0 when you clear out the gmarkers array.

    Change:

    function rungooglemap(value) {
        for(i=0; i<gmarkers.length; i++){
            gmarkers[i].setMap(null);
        }
        nextAddress = 0;        
        theNext();           
    }
    

    To:

    function rungooglemap(value) {
        for(i=0; i<gmarkers.length; i++){
            gmarkers[i].setMap(null);
        }
        // empty the array
        gmarkers = [];
        // set the index for the geocoding loop back to the beginning
        nextAddress = 0;        
        infovalue = 0;
        theNext();           
    }
    

    updated code snippet:

    var locations = [];
    var markersinfo = [];
    var gmarkers = [];
    
    //all events function
    function allevents() {
      $('#checkinstatus').val('');
    
      for (i = 0; i < gmarkers.length; i++) {
        gmarkers[i].setMap(null);
      }
    
      locations = [];
      markersinfo = [];
    
      var parseddata = [{
          "Start_DateTime": "2018-08-06T19:00:00+10:00",
          "Event_Title": "testing event creation 5",
          "End_DateTime": "2018-08-06T19:30:00+10:00",
          "dateforfilter": "2018-08-26",
          "Check_In_Status": "PLANNED",
          "Venue": "1 Street Name City NSW 0000 Australia",
        },
        {
          "Start_DateTime": "2018-08-06T17:00:00+10:00",
          "Event_Title": "testing event creation 6",
          "End_DateTime": "2018-08-06T17:30:00+10:00",
          "dateforfilter": "2018-08-26",
          "Check_In_Status": "PLANNED",
          "Venue": "3111  Sampson Street Aurora Colorado 80014 US",
        }
      ];
    
      var allevents = parseddata;
      for (i = 0; i < allevents.length; i++) {
    
        var locobj = allevents[i].Venue;
        var markersobj = ['<div class="info_content">' + '<h3>' + allevents[i].Event_Title + '</h3>' + '<p>CheckIn-Status:' + allevents[i].Check_In_Status + '</p>' + '</div>'];
    
        if (locobj == null) {
    
        } else {
          markersinfo.push(markersobj);
          locations.push(locobj);
        }
    
      }
      rungooglemap();
    };
    
    //CheckedIn-Status based filters
    function getcheckinlocationfilter() {
    
    
      var x = document.getElementById("checkinstatus").value;
      //console.log('checkinstatus filter', x);
      if (x == 'VISITED') {
        for (i = 0; i < gmarkers.length; i++) {
          gmarkers[i].setMap(null);
        }
    
        var parseddata = [{
            "Start_DateTime": "2018-08-06T19:00:00+10:00",
            "Event_Title": "testing event creation 3",
            "End_DateTime": "2018-08-06T19:30:00+10:00",
            "dateforfilter": "2018-08-26",
            "Check_In_Status": "PLANNED",
            "Venue": "2851 Jacobs Street Coraopolis PA Pennsylvania 15108",
          },
          {
            "Start_DateTime": "2018-08-06T17:00:00+10:00",
            "Event_Title": "testing event creation 4",
            "End_DateTime": "2018-08-06T17:30:00+10:00",
            "dateforfilter": "2018-08-26",
            "Check_In_Status": "PLANNED",
            "Venue": "mysuru museum karnataka",
          },
          {
            "Start_DateTime": "2018-08-06T19:00:00+10:00",
            "Event_Title": "testing event creation 3",
            "End_DateTime": "2018-08-06T19:30:00+10:00",
            "dateforfilter": "2018-08-26",
            "Check_In_Status": "PLANNED",
            "Venue": "5 Carter St South Melbourne",
          },
          {
            "Start_DateTime": "2018-08-06T17:00:00+10:00",
            "Event_Title": "testing event creation 4",
            "End_DateTime": "2018-08-06T17:30:00+10:00",
            "dateforfilter": "2018-08-26",
            "Check_In_Status": "PLANNED",
            "Venue": "Adyar Ananda Bhavan, 7, Mahatma Gandhi Road, Shastri Nagar, Adyar, Chennai, Tamil Nadu 600020",
          },
    
        ];
        var checkedinevents = parseddata;
    
        locations = [];
        markersinfo = [];
    
        for (i = 0; i < checkedinevents.length; i++) {
          var locobj = checkedinevents[i].Venue;
          console.log(locobj);
          var markersobj = ['<div class="info_content">' + '<h3>' + checkedinevents[i].Event_Title + '</h3>' + '<p>From : ' + checkedinevents[i].Start_DateTime + '</p>' + '<p>To :' + checkedinevents[i].End_DateTime + '</p>' + '</div>'];
    
          if (locobj == null) {
            //console.log('There is no address in the event');
          } else {
            // console.log('not a null',locobj);
            markersinfo.push(markersobj);
            locations.push(locobj);
          }
        }
    
    
        rungooglemap();
    
      } else if (x == 'PLANNED') {
        // console.log('PLANNED');
      } else {
        //console.log('select option');
      }
    }
    
    
    //google map part starts here
    var nextAddress = 0;
    var infovalue = 0;
    var delay = 100;
    var infowindow = new google.maps.InfoWindow();
    var latlng = new google.maps.LatLng(21.0000, 78.0000);
    var mapOptions = {
      zoom: 5,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      //gestureHandling: 'greedy',
    }
    var geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    var bounds = new google.maps.LatLngBounds();
    
    
    //geocoding address conversion function
    function geocodeAddress(address, next) {
      geocoder.geocode({
        address: address
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var p = results[0].geometry.location;
          var lat = p.lat();
          var lng = p.lng();
          createMarker(infovalue, lat, lng);
          infovalue++;
        } else {
          if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            nextAddress--;
            delay++;
          } else {}
        }
        next();
      });
    }
    
    //markers creation and info window data handling
    function createMarker(add, lat, lng) {
      var image = 'gps2.png';
    
      var contentString = add;
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        //icon: new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"),
      });
    
      //clear the previous locations
      gmarkers.push(marker);
    
      //Create and open InfoWindow.
      var infoWindow = new google.maps.InfoWindow();
    
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent("<div style = 'width:200px;min-height:40px'>" + markersinfo[add] + "</div>");
        infowindow.open(map, marker);
      });
    
      bounds.extend(marker.position);
    }
    
    //based on the address count calling a geocoding function one by one 
    function theNext() {
      if (nextAddress < locations.length) {
        setTimeout('geocodeAddress("' + locations[nextAddress] + '",theNext)', delay);
        nextAddress++;
      } else {
        map.fitBounds(bounds);
      }
    }
    
    //forwarding from individual functions to google api
    function rungooglemap(value) {
      for (i = 0; i < gmarkers.length; i++) {
        gmarkers[i].setMap(null);
      }
      gmarkers = [];
      nextAddress = 0;
      infovalue = 0;
      theNext();
    }
    html {
      height: 100%
    }
    
    body {
      height: 100%;
      margin: 0;
      padding: 0
    }
    
    #map {
      width: 100%;
      height: 100%;
    }
    
    .button {
      border-radius: 4px;
      background-color: #f4511e;
      border: none;
      color: #FFFFFF;
      text-align: center;
      font-size: 28px;
      padding: 20px;
      width: 200px;
      transition: all 0.5s;
      cursor: pointer;
      margin: 5px;
    }
    
    .button span {
      cursor: pointer;
      display: inline-block;
      position: relative;
      transition: 0.5s;
    }
    
    .button span:after {
      content: '\00bb';
      position: absolute;
      opacity: 0;
      top: 0;
      right: -20px;
      transition: 0.5s;
    }
    
    .button:hover span {
      padding-right: 25px;
    }
    
    .button:hover span:after {
      opacity: 1;
      right: 0;
    }
    
    select {
      background-color: #f9fbfb;
      border: 1px solid #c6cbd4;
      border-radius: 4px;
      height: 40px;
      margin-top: 5px;
      margin-bottom: 20px;
      padding: 8px;
      font-size: 14px;
      outline: none;
      width: 100%;
      -webkit-appearance: none;
      appearance: none;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Account Locations</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyB3pwJBXen9pU6syjpqZHQvoeZOEYoPWsM">
      </script>
    </head>
    
    <body>
    
      <div style="float:left;width:100%;margin-bottom:0px;margin-top:15px;">
    
        <div style="float:left;width:50%;text-align:center;">
          <button class="button" style="height:80px;" name="allevents" onclick="allevents()" value="allevents"><span style="margin-top: -12px;"> function 1</span></button>
        </div>
    
        <div style="float:left;width:50%;text-align:center;">
          <h1 style="margin-top: 0px;height:10px;color: #f4511e;">function 1</h1>
          <select name="checkinstatus" id="checkinstatus" onchange="getcheckinlocationfilter()" style="border-color: coral;border-bottom-width: 5px;width: 60%;">
            <option value="Select any one option"> Select any one option </option>
            <option value="VISITED"> visited </option>
            <!-- <option value="PLANNED"> planned </option>  -->
          </select>
        </div>
    
      </div>
    
      <!-- google map div-->
      <div id="map"></div>
    
    </body>
    
    
    </html>