Google Maps API地理编码功能问题

时间:2011-08-24 08:44:29

标签: google-maps-api-3 javascript

好吧,我正在和Google Maps API v3搞砸,我碰到了一个问题。我不知道它是API还是我做的一些JS错误。

问题: addMarkerFromAdress()上的geocodeFromAdress()函数调用将坐标返回addMarkerFromAdress()。但返回值为“ undefined ”。

作为调试,我添加了两个警报输出,一个在addMarkerFromAdress(),另一个在geocodeFromAdress()。令我感到困扰的是alert()中的addMarkerFromAdress()似乎在返回任何值之前触发。为什么呢?

来源:

<script type="text/javascript">
  var geocoder;
  var map;

  function initializeGoogleMaps() {

    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(0, 0);
    var myOptions = {
      zoom: 1,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  }

  function geocodeFromAdress(address) {
   geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latLng = results[0].geometry.location;
        alert(latLng); //Outputs coordinates, but is for some reason outputted 2nd
        return latLng;
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

  function addMarkerFromAdress(address, title){

    var latLng = geocodeFromAdress(address); 
    alert(latLng); //Outputs "undefined", but is for some reason outputted 1st
    map.setCenter(latLng);
        var marker = new google.maps.Marker({
            map: map, 
            position: latLng
    });

  }

  window.onload = function () { 
   initializeGoogleMaps();
   addMarkerFromAdress('Berlin, Germany', 'Berlin');
  }
</script>

1 个答案:

答案 0 :(得分:4)

将该函数作为第二个参数传递给geocoder.geocode()?那是你应该打电话给addMarkerFromAddress的地方。由于地理编码请求的异步性质,alert之后的var latLng = geocodeFromAdress(address);在使用lat long值返回响应之前触发。

这样的事情应该这样做

<script type="text/javascript">
  var geocoder;
  var map;

  function initializeGoogleMaps() {

    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(0, 0);
    var myOptions = {
      zoom: 1,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  }

  function geocodeFromAdress(address, title) {
   geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var latLng = results[0].geometry.location;
        addMarkerFromAdress(latLng, title);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

  function addMarkerFromAdress(latLng, title){
    map.setCenter(latLng);
    var marker = new google.maps.Marker({
        map: map, 
        position: latLng
    });   
  }

  window.onload = function () { 
   initializeGoogleMaps();
   geocodeFromAdress('Berlin, Germany', 'Berlin');
  }
</script>