如何使用Google Javascript v3 Geocoder返回经纬度数组? [英] How do you return a latitude and longitude array using the Google Javascript v3 Geocoder?

查看:113
本文介绍了如何使用Google Javascript v3 Geocoder返回经纬度数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个利用Google Javascript V3的地理编码功能的函数,并返回一个具有经度和纬度的数组。出于某种原因,返回数组没有使用该函数进行填充。感谢您的帮助!

I'm trying to create a function that utilizes Google Javascript V3's geocoding capabilities and returns an array with the longitude and latitude. For some reason the return array is not being populated using the function. Thanks for your help!

代码:

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

  var test_arr;    
  test_arr = getLatLng('New York');
  alert(test_arr[0] + ',' + test_arr[1]) // I'm getting a test_arr is undefined here.


推荐答案

阅读使用Javascript中的回调函数。 这篇文章可能会有帮助。

Read up on using callback functions in Javascript. This article might be helpful.

正如Jon指出的那样,您可以通过将回调函数传递给getCoords方法来解决此问题。这是一种等待Google回应的方式。您定义了一个函数,当地理编码完成时将会调用该函数。

As Jon pointed out, you can solve this by passing a callback function into your getCoords method. It's a way of waiting for the response to come back from Google. You define a function that will be called when the geocoding is done. Instead of returning the data, you'll call the provided function with the data as an argument.

类似这样的内容:

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

getCoords('New York', function(latLng) {
  var test_arr;
  test_arr = latLng;
  alert(test_arr[0] + ',' + test_arr[1])
  // Continue the rest of your program's execution in here
});

这篇关于如何使用Google Javascript v3 Geocoder返回经纬度数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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