Every infowindow is displaying the same data maps api v3

删除回忆录丶 提交于 2019-12-25 19:42:56

问题


I am really stuck on something. Every map marker's infowindow is displaying the same info. It seems to be the content at the end of an array that i use to store content nodes every time. I am pretty sure it is because the infowindow is not being attached to the proper marker

    var markers = [];
    var contentArray = [];
    var titleArray = [];
    var latlngArray = [];
    var map;
    //var infowindow;
    var concert;

    function defaultMap()
    {
        //Latitude: 38
        //Longitude: -97
        //window.alert("inside function");
        var mapOptions = {
          center:new google.maps.LatLng(38,-97),
          zoom:4,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map"),
                                  mapOptions);


           // window.alert("addMarkers the size of contentArray is: "+contentArray.length);
       //window.alert("addMarkers the size of the titleArray is: "+titleArray.length);
       // window.alert("addMarkers the size of the latLongArray is: "+latlngArray.length);



        //for(var i =0;i<2;i++)
        //{
        //    if(i == 0)
        //    {
        //        marker = new google.maps.Marker({
        //           position: new google.maps.LatLng(37.8172784,-96.8909115),
        //           map:map
        //        });
        //        markers.push(marker);
        //    }
        //    else
        //    {
        //        marker = new google.maps.Marker({
        //           position: new google.maps.LatLng(37.8172973,-96.8766355),
        //           map:map
        //        });
        //        markers.push(marker);
        //    }
        //    //markers[0] = new google.maps.LatLng(37.8172784,-96.8909115);
        //    //markers[1] = new google.maps.LatLng(37.8172973,-96.8766355);
        //    
        //}
        //addMarkers();
    }

    //function 


            //
            //{
            //infowindow = new google.maps.InfoWindow({
            //content:list
            //});
            //google.maps.event.addListener(marker,'click',function(){
            // infowindow.open(map,marker);
            //});


    function addMarkers()
    {
        //console.dir(contentArray[contentArray.length-1]);
        for(var i = 0;i <10;i++)
        {
            if(i == 0)
            {
                //window.alert("i = "+i);
                console.log(latlngArray[i]);
                var marker = new google.maps.Marker({
                   position:latlngArray[i],
                   animation:google.maps.Animation.DROP,
                   icon:'./images/club.png',
                    title:titleArray[i],
                   map:map
                });

                //marker.setMap(map);
                            var infowindow = new google.maps.InfoWindow({

                });

                google.maps.event.addListener(marker,'click',function()
                                              {
                                                //console.log(infowindow.getContent());
                                                infowindow.setContent(contentArray[i]);
                                                infowindow.open(map,this);
                                              });
                markers.push(marker);

            }
            else
            {
                console.log(latlngArray[i]);
                var marker = new google.maps.Marker({
                   position:latlngArray[i],
                   animation:google.maps.Animation.DROP,
                   icon:'./images/restaurant.png',
                   title:titleArray[i],
                   map:map
                });

                var infowindow = new google.maps.InfoWindow({});
                            //console.log(infowindow.getContent());

                google.maps.event.addListener(marker,'click',function()
                {

                  infowindow.setContent(contentArray[i]);
                  console.log(infowindow.getContent());
                  infowindow.open(map,this);
                });
                 markers.push(marker);
            }

            //console.log(i);
            //console.log(contentArray[i]);
        }
    }

回答1:


The problem is that when the loop ends, i is 10. Every infowindow displays:

 infowindow.setContent(contentArray[i]);

There are two ways to solve the problem:

  1. function closure. Use a createMarker function to associate the infowindow content with the marker. Explained in Mike Williams' v2 tutorial, one of his examples using function closure, translated to v3.
  2. marker member variable containing the content, access it in the click listener by referencing "this". The answer to this similar question may help with this. Here is an example of using a member variable of the marker



回答2:


This Code is also for all those who want to put multiple Markers on Map retrieved from DB

i am going to paste a Code of live project means working. you can get some help from this.

function latLongCallback(latitutde,longitutde){
 var latlng = new google.maps.LatLng(latitutde, longitutde);
    var options  = {zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
    var map      = new google.maps.Map(document.getElementById('map'), options);

    $.ajax({type: "GET",
      dataType: 'json',
     url: 'https://www.xyz.com/yourrfolder/markers.php',
    success: function(response){
         var total=response.length;
         var data_array,name,type,address,lat,lon,arrival,departure,notes;
          var infowindow = new google.maps.InfoWindow();   
       for(var i=0; i < total; i++){
            data_array=response[i];
            name=data_array['name'];
            id = data_array['id'];
            address=data_array['address'];
            arrival=data_array['arrival'];
            departure=data_array['departure'];
            notes=data_array['notes'];
            lat=data_array['lat'];
            lon=data_array['lon'];
            icon=data_array['icon'];
            sc_id=data_array['sc_id'];

var propPos = new google.maps.LatLng(lat,lon);
            propMarker = new google.maps.Marker({
                position: propPos,
                map: map,
                icon: icon,
                zIndex: 3
            });

var contentString = "<div style='font-size:9px;overflow:hidden'>"+name+"<br/><label class='label'>Location :</label> "+address+"<br/><label class='label'>Arrival :</label> "+arrival+"<br/><label class='label'>Departure :</label> "+departure+"<br/><label class='label'>Notes :</label> "+notes + "</div><div style='font-size:9px;overflow:hidden'><a href='#2' onclick="+xx+" class='popup-txt' style='font-size:11px; margin-top:3px;'>Message him</a><a href='#1' onclick="+invite+" class='popup-txt' style='font-size:11px; margin-top:3px; float:right;'>Invite Friend</a></div>"; 

   function bindInfoWindow(marker, map, infowindow, html) {
         google.maps.event.addListener(marker, 'click', function() {
                    infowindow.setContent(html);
                    infowindow.open(map, marker);
                });
 bindInfoWindow(propMarker, map, infowindow, contentString);
     }
    }
});
return; 
}

and here is the marker.php mentioned in above js

<?php 
  $data=array();
  $retrive_marker_query = "your query";
  $result               =    db_execute($retrive_marker_query);
  $cnt=0;

while ($row = mysql_fetch_assoc($result)){
 $name      = $row['name'];
 $id        = $row['fb_id'];
 $sc_id     = $row['id'];
 $address   = $row['location'];
 $lat       = $row['lat'];
 $lon       = $row['lon'];


   $data[$cnt]['name']    = $name;
   $data[$cnt]['id']      = $id;
   $data[$cnt]['sc_id']   = $sc_id;
   $data[$cnt]['address'] = $address;
   $data[$cnt]['lat']     = $lat;
   $data[$cnt]['lon']     = $lon;

   $cnt++;
   }
$data=json_encode($data);
 echo($data);
<?


来源:https://stackoverflow.com/questions/13336600/every-infowindow-is-displaying-the-same-data-maps-api-v3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!