繁体   English   中英

Google Maps API与地址解析器有关的问题

[英]Google maps API issue with geocoder

我认为我只是在做一些愚蠢的事情,因为我的JavaScript技能不是最出色的。 以下代码生成空白的灰色地图:

function initialize() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        geocoder = new google.maps.Geocoder();
        var address = "Minneapolis, MN";
        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();
               addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());  
           }
           else
           {
                   alert(status);
           }
        });
        var mapOptions = {
          zoom: 7,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          center: addresslatlng
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('directions-panel'));
      }

但是,如果仅将“ center:addresslatlng”更改为:

center: new google.maps.LatLng(-34.397, 150.644)

工作正常。

我尝试使用latlng ,但也不起作用:

center: new google.maps.LatLng(lat, lng)

有任何想法吗?

地理编码是异步的。 您需要在回调函数中使用结果:

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var address = "Minneapolis, MN";
    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();
           addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());  
    var mapOptions = {
      zoom: 7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: addresslatlng
    };
    var map = new google.maps.Map(document.getElementById('map_canvas'),
        mapOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directions-panel'));
       }
       else
       {
               alert(status);
       }
    });
  }

工作实例

我认为这

lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();

真的应该更像这样

lat = results[0].geometry.location.lat;
lng = results[0].geometry.location.lng;

同样,您创建latlon ,然后不要在下一行中使用它们。 改变这个

addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());

对此

addresslatlng = new google.maps.LatLng(lat, lng);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM