【问题标题】:Google Maps V3 infowindows displaying wrong content on pinsGoogle Maps V3 信息窗口在图钉上显示错误内容
【发布时间】:2015-05-20 11:32:56
【问题描述】:

我正在绘制地址,但每次显示正确内容的信息窗口都有问题。有时它会在单击时在信息窗口中显示正确的内容,有时它会显示该地图图钉的错误信息。

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>

【问题讨论】:

  • 你的阵列是什么样的?请提供一个 Minimal, Complete, Tested and Readable example 来证明该问题。
  • 我将包含地址、标题和其他信息的变量推送到上面称为“addMarker”的函数中,我会循环、地理编码和绘图。绘制它们时,信息窗口不会显示该地图图钉的正确信息。

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


【解决方案1】:

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

  1. 使用函数闭包将标记与信息窗口相关联
  2. 使用函数闭包将地址与标记相关联
  3. 在其回调函数中使用地理编码器的结果。

请注意,如果您的阵列中有超过大约 10 个标记,您将遇到地理编码器的配额/速率限制。

proof of concept fiddle

代码sn-p:

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>

【讨论】:

【解决方案2】:

由于您没有提供有效的 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-06
    • 2011-03-23
    • 1970-01-01
    • 2012-06-07
    • 2014-05-14
    • 1970-01-01
    • 2012-09-06
    • 2013-10-10
    相关资源
    最近更新 更多