Информационное окно для нескольких динамических местоположений на карте Google не отображается должным образом - PullRequest
0 голосов
/ 25 августа 2018

Информационное окно карты Google не отображает детали при обновлении массива новых местоположений.

см. : вызовите function1 и щелкните маркер, там вы можете увидеть детали информационного окна.но когда я пытаюсь выполнить function2 после function1, информационное окно показывает неопределенное .. см. изображение здесь для справки

примечание: это просто пример файла с той же функциональностью, что и мой исходный файл.

    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>

1 Ответ

0 голосов
/ 25 августа 2018

Вы не устанавливаете переменную infovalue обратно в 0, когда очищаете массив gmarkers.

Изменение:

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

Кому:

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();           
}

обновленный фрагмент кода:

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>
...