Google使用地理编码器映射API问题 [英] Google maps API issue with geocoder

查看:63
本文介绍了Google使用地理编码器映射API问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我只是在做一些愚蠢的事情,因为我的JavaScript技能并不是最棒的。以下代码会生成空白灰色贴图:

I think I'm just doing something stupid because my javascript skills aren't the greatest. The following code produces a blank, gray map:

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更改为:

However, if simply change the "center: addresslatlng" to:

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

它工作正常。

我尝试过使用 lat lng ,但这也不起作用:

I tried using lat and lng and that does NOT work either:

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

有什么想法?

Any ideas?

推荐答案

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

Geocoding is asynchronous. You need to use the results inside the call back function:

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);
       }
    });
  }

工作示例

这篇关于Google使用地理编码器映射API问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆