使用google.maps.Geocoder()。异步回调

时间:2013-02-13 00:41:01

标签: javascript asynchronous callback google-geocoder

我一直在尝试将地址地理编码为LatLng坐标,但我遇到了很多困难。我知道geocode()是一个异步函数,我一直在玩回调而无济于事。我一直在寻找像这样的其他帖子(How to return value from an asynchronous callback function?),但我很难理解这个概念。如果有人能告诉我如何正确地做回调函数,将不胜感激。这一次很头疼。能够获得回调以执行提供正确LatLng的alert(),但不设置位置参数。抱歉无法从前面引用的例子中弄清楚。对语言来说很新鲜。您可以指出我理解这个概念的任何参考资料也非常受欢迎。谢谢!

  var location;
  var image;
  var map;
  var geocoder;
  var address;

  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(42.763146, -73.3776),
      zoom: 6,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        mapOptions);
    var cloudLayer = new google.maps.weather.CloudLayer();
    cloudLayer.setMap(map);

    addressSet(function(address) {
        console.log(address);
        // tried to set location = address;, location = new google.maps.LatLng(address);
        // neither works
    });

    addMtsToMap(location,
                map,
                new google.maps.MarkerImage("img/mts/skier.png", null, null, null, new google.maps.Size(50,50)));

  }

  function addMtsToMap(location, map, image) {

    var marker = new google.maps.Marker({
        position: location,
        map: map,
        icon: image
    });

    var infoWindow = new google.maps.InfoWindow({content: "<h1>Powder!!!</h1>"});

    google.maps.event.addListener(marker, "click", function() {
        infoWindow.open(map, marker);
    });
  }

  function addressSet(callback) {

    geocoder = new google.maps.Geocoder();

    geocoder.geocode({address: "Killington+VT"}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            address = results[0].geometry.location;
            callback(address);
        }
    });
  }

1 个答案:

答案 0 :(得分:0)

对不起所有人。在弄乱了这么久之后,无法相信我发现的东西。我在初始化时再次声明var map,这使我的addressSet()函数拉出了错误的全局映射变量。删除var使它工作。