Google Maps V3 infowindows在引脚上显示错误的内容

时间:2015-05-19 21:04:21

标签: javascript google-maps google-maps-api-3

我正在绘制地址并且每次都显示正确内容的infowindow存在问题。有时它在点击时会在infowindow中显示正确的内容,有时它会显示该地图图钉的错误信息。

var map = null;
var markersArray = [];
var markers = [];
var openedInfoWindow ="";
var geocoder = new google.maps.Geocoder();

function initialize() {

    var mapOptions = {

     zoom: 8,
      center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapInfoManual"),
        mapOptions);

    google.maps.event.addListener(map, 'zoom_changed', function() {
        zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
            if (this.getZoom() > 20) // Change max/min zoom here
                this.setZoom(18);

            google.maps.event.removeListener(zoomChangeBoundsListener);
        });
});
    addMarker();
  }

function addMarker() {

        var bounds = new google.maps.LatLngBounds();
        for(i=0; i<markersArray.length; i++)
        {
            CodeAddress(markersArray[i]['address']);
            var mytitle = (markersArray[i]['title']);
            var myaddress = (markersArray[i]['displayaddress']);
            var linkurl = (markersArray[i]['linkurl']);

        }
        setTimeout(function()
        {

          for(i=0; i<markers.length; i++)
          {
              var point = new google.maps.LatLng(markers[i]['lat'], markers[i]['lng']);

              var marker = new google.maps.Marker({
                  position: point,
                  map: map
              });
              bounds.extend(point);
              var infoWindowContent = "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>"+ mytitle +"</div><div style='margin-bottom:5px;'>" + myaddress + "</div><div><a href='" + linkurl + "/'>More Details</a></div></div>";

              openInfoWindow(marker,infoWindowContent)      

          }
          map.fitBounds(bounds);

          },2500);

}

// Address To Marker
function CodeAddress(address)
{

    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        lat = results[0].geometry.location.lat();
        lng = results[0].geometry.location.lng();
        markers.push({
                        'lat':lat,
                        'lng':lng,
                        'address':address
                    }); 
    } 

});   
}
//Info Window
function openInfoWindow(marker,infoWindowContent)
{   
    var infowindow = new google.maps.InfoWindow({
        content: '<div class="cityMapInfoPop">'+infoWindowContent+'</div>'          
    });

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

        if(openedInfoWindow !="")
        {
            openedInfoWindow.close()
        }

        infowindow.open(map,marker);
        openedInfoWindow = infowindow;
    });
}

我传入的变量:

 <script type="application/javascript">
     markersArray.push({
    "title":'<?php echo $maptitle;?>',
    "address":'<?php echo $markerAddress;?>',
    "displayaddress":'<?php echo $displayAddress;?>',
    "linkurl":'<?php echo $addressUrl;?>'
     });    
</script>

2 个答案:

答案 0 :(得分:0)

由于您没有提供有效的JSFiddle,因此很难弄清楚您的问题是什么。也就是说,你可以look at this JSFiddle我为你做的事情来回顾我正在做的事情和你正在做的事情。

为什么使用setTimeout()来放置标记?此外,如果您为每个标记创建单独的infoWindow,而不是使用“全局”infoWindow(这就是您正在执行的操作),则可能会获得更好的结果。

如果您编辑帖子以添加问题的实际示例,我可以提供进一步的帮助。

window.places = [{
  title: "foo",
  address: {
    lat: parseFloat("64.85599578876611"),
    lng: parseFloat("-147.83363628361917")
  },
  displayAddress: "101 BLVD",
  linkURL: "google.com"
}, {
  title: "bar",
  address: {
    lat: parseFloat("62.85599578876611"),
    lng: parseFloat("-147.83363628361917")
  },
  displayAddress: "202 BLVD",
  linkURL: "images.google.com"
}, ]

function initialize() {
  "use strict";
  var myLatlng = new google.maps.LatLng(window.places[0].address.lat, window.places[0].address.lng),
    mapOptions = {
      zoom: 4,
      center: myLatlng
    };

  window.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  $.each(window.places, function(i) {

    var infowindow = new google.maps.InfoWindow({
        content: "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>" + window.places[i].title + "</div><div style='margin-bottom:5px;'>" + window.places[i].displayAddress + "</div><div><a href='" + window.places[i].linkURL + "/'>More Details</a></div></div>"
      }),
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(window.places[i].address.lat, window.places[i].address.lng),
        map: window.map,
        title: window.places[i].title
      });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(window.map, marker);
    });

  });
}

google.maps.event.addDomListener(window, 'load', initialize);
      html,
      body,
      #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<div id="map-canvas"></div>

答案 1 :(得分:0)

您的问题是地理编码是异步的。您通过在所有地址上调用地理编码器来循环,但返回结果的顺序是不可预测的。

  1. 使用函数闭包将标记与infowindow相关联
  2. 使用函数闭包将地址与标记
  3. 相关联
  4. 在其回调函数中使用地理编码器的结果。
  5. 请注意,如果阵列中有大约10个标记,则会遇到地理编码器的配额/速率限制。

    proof of concept fiddle

    代码段:

    var map = null;
    var markersArray = [];
    var markers = [];
    var openedInfoWindow = "";
    var geocoder = new google.maps.Geocoder();
    var bounds = new google.maps.LatLngBounds();
    
    markersArray.push({
      "title": 'marker 0',
      "address": 'New York,NY',
      "displayaddress": 'New York, NY',
      "linkurl": 'http://google.com'
    });
    markersArray.push({
      "title": 'marker 1',
      "address": 'Boston, MA',
      "displayaddress": 'Boston, MA',
      "linkurl": 'http://yahoo.com'
    });
    markersArray.push({
      "title": 'marker 2',
      "address": 'Newark,NJ',
      "displayaddress": 'Newark, NJ',
      "linkurl": 'http://mapquest.com'
    });
    google.maps.event.addDomListener(window, "load", initialize);
    
    function initialize() {
    
      var mapOptions = {
    
        zoom: 8,
        center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById("mapInfoManual"),
        mapOptions);
    
      google.maps.event.addListener(map, 'zoom_changed', function() {
        zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
          if (this.getZoom() > 20) // Change max/min zoom here
            this.setZoom(18);
    
          google.maps.event.removeListener(zoomChangeBoundsListener);
        });
      });
      addMarker();
    }
    
    function addMarker() {
    
      var bounds = new google.maps.LatLngBounds();
      for (i = 0; i < markersArray.length; i++) {
        CodeAddress(markersArray[i]);
      }
    }
    
    // Address To Marker
    function CodeAddress(markerEntry) {
        var mytitle = (markerEntry['title']);
        var myaddress = (markerEntry['displayaddress']);
        var linkurl = (markerEntry['linkurl']);
        geocoder.geocode({
          'address': markerEntry['address']
        }, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({
              position: results[0].geometry.location,
              map: map
            });
            bounds.extend(marker.getPosition());
            var infoWindowContent = "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>" + mytitle + "</div><div style='margin-bottom:5px;'>" + myaddress + "</div><div><a href='" + linkurl + "/'>More Details</a></div></div>";
    
            openInfoWindow(marker, infoWindowContent);
            markers.push(marker);
            map.fitBounds(bounds);
          } else {
            alert("geocode failed: " + status);
          }
        });
      }
      //Info Window
    
    function openInfoWindow(marker, infoWindowContent) {
      var infowindow = new google.maps.InfoWindow({
        content: '<div class="cityMapInfoPop">' + infoWindowContent + '</div>'
      });
    
      google.maps.event.addListener(marker, 'click', function() {
    
        if (openedInfoWindow != "") {
          openedInfoWindow.close();
        }
    
        infowindow.open(map, marker);
        openedInfoWindow = infowindow;
      });
    }
    html,
    body,
    #mapInfoManual {
      height: 500px;
      width: 500px;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js?ext=.js"></script>
    <div id="mapInfoManual" style="border: 2px solid #3872ac;"></div>