谷歌地图API v.3-无法显示信息窗口,或者当我这样做时,地图的中心位于设计位置



我在使用Google Maps的API v.3时遇到了一个小问题。我从MySql数据库中获取位置地址,并尝试将其动态发送到GMaps。这还可以,但我似乎无法打开"信息窗口"。如果代码有点乱,但我最接近的解决方案是打开信息窗口,但地图集中在定义位置,而不是实际位置。我搜索了不同的网站,但找不到合适的建议。也许我正在混合v.2和v.3,但据我所见,情况似乎并非如此。这是我第一次看到谷歌的API,所以请耐心等待。所有代码都来自示例:

  var marker;
  var geocoder;
  var map;
  function initialize() {
    var mapDiv = document.getElementById('map-canvas');
    var latlng = new google.maps.LatLng(42.696492,23.326011);
      geocoder = new google.maps.Geocoder();
      var address = "Milano 20099";
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
          marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location
          });
        } else {
          // alert("Geocode was not successful for the following reason: " + status);
        }
      });
      var infowindow = new google.maps.InfoWindow({content: '<strong>I will be here!</strong><br/>Milano 20099'});
      var myOptions = {
        zoom: 9,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.HYBRID
      }
      map = new google.maps.Map(mapDiv, myOptions);
      infowindow.open(map, marker);
  }

提前感谢!

您必须将信息窗口打开方法移动到地理编码器成功回调函数。地理编码请求可能需要一段时间才能响应,并且您正试图在地理编码返回标记位置之前打开一个信息窗口。所以你的代码应该如下:

var marker;
            var geocoder;
            var map;
            function initialize() {
                var latlng = new google.maps.LatLng(42.696492, 23.326011);
                var myOptions = {
                    zoom : 9,
                    center : latlng,
                    mapTypeId : google.maps.MapTypeId.HYBRID
                }
                var mapDiv = document.getElementById('map-canvas');
                map = new google.maps.Map(mapDiv, myOptions);
                geocoder = new google.maps.Geocoder();
                var address = "Milano 20099";
                geocoder.geocode({
                    'address' : address
                }, function(results, status) {
                    if(status == google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                        marker = new google.maps.Marker({
                            map : map,
                            position : results[0].geometry.location
                        });
                        var infowindow = new google.maps.InfoWindow({
                    content : '<strong>I will be here!</strong><br/>Milano 20099'
                });

                infowindow.open(map, marker);
                    } else {
                        // alert("Geocode was not successful for the following reason: " + status);
                    }
                });
            }

相关内容

最新更新