繁体   English   中英

Google Maps API3错误

[英]Error with google maps api3

我正在尝试在网页中嵌入带有标记的Google地图。 但是,如果使用以下代码,则会收到未定义的警报消息

var infowindow = null;
var geocoder;
$(document).ready(function () { initialize();  });

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //alert(results[0].geometry.location);
            return (results[0].geometry.location);
        } 
    });
}

function initialize() {
    default_location = codeAddress("<?php echo $location;?>");
    alert(default_location);
}

相反,如果我在下面的codeAdress函数中执行警报,则它正确显示了纬度和经度。

var infowindow = null;
var geocoder;
$(document).ready(function () { initialize();  });

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert(results[0].geometry.location);

        } 
    });
}

function initialize() {
    codeAddress("<?php echo $location;?>");
}

有人可以找出问题所在吗? 我是javascript新手

地理编码器调用是异步的,这意味着返回会花费一些时间,并且不会遵循写入的顺序。 这也意味着在第一位,该函数在return (results[0].geometry.location)语句之前完成。 因此, alert没有任何显示。

除了在geocode请求中插入语句外,您还可以编写回调模式来分隔脚本逻辑。 geocode调用成功后,将执行将位置作为参数传递的回调。

http://jsfiddle.net/3KXKm/

  var infowindow = null;
  var geocoder = new google.maps.Geocoder();

  $(document).ready(function () { initialize();  });

  function codeAddress(address, callback) {
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        callback(results[0].geometry.location);
      } 
    });
  }

  function initialize() {
    codeAddress("Chicago, IL", function(default_location) {
      var map = new google.maps.Map(document.getElementById("map_canvas"),
        { center: default_location,
        zoom: 3, mapTypeId: google.maps.MapTypeId.ROADMAP });

      locations = ["Los Angeles", "Davis", "Truth or Consequences",
        "Ann Arbor", "Massachusetts"];

      for (var i = 0; i < locations.length; i++) {
        codeAddress(locations[i], function(latLng) {
          new google.maps.Marker({map:map, position:latLng});
        });
      }
    });
  }

地理编码不会立即返回结果。 这就是为什么在第一版代码中什么都看不到的原因。 因此,如果您要对地址解析结果进行处理,则应在回调函数中进行处理,例如在第二版代码中。

你的

return (results[0].geography.location);

仅返回嵌套函数的值,而不返回codeAddress函数的值。 也许如果您告诉我们您要做什么,我们可以为您提供帮助。

暂无
暂无

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

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