使用google.maps.geocoder检索位置的纬度/经度 [英] retrieving lat/long of location using google.maps.geocoder

查看:98
本文介绍了使用google.maps.geocoder检索位置的纬度/经度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用一些ajax来保存应用程序中的场地位置,并在堆栈溢出中偶然发现了以下代码:

i have been trying to use some ajax to save venue location in my application and stumbled across the following code on stack overflow

function getLatLong(address) 
{
    var geocoder = new google.maps.Geocoder();
    var result = "";
    geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            result[lat] = results[0].geometry.location.Pa;
            result[lng] = results[0].geometry.location.Qa;
        } else {
            result = "Unable to find address: " + status;
        }
    });
    return result;
}

我的问题是当我调用函数时,它什么也没有返回,在chrome中设置断点,它在返回结果中断之前首先在结果上打破[lat] = results [0] .geometry.location.Pa;

my problem is when i call the function it returns nothing and when i debug and set breakpoints in chrome it breaks on return result first before it breaks on the result[lat] = results[0].geometry.location.Pa;

我知道数组应该被声明为类型数组,但即使当我刚刚返回结果[0] .geometry.location对象时,也没有任何东西被返回

I know the array should be declared as type array but even when i was just returning the results[0].geometry.location object nothing was being returned

我可以做些什么来返回位置的纬度/经度,这样我就可以存储在我的数据库中?

what can i do to return the lat/long of the location so i can store in my db?

推荐答案

您遇到的问题是您在执行返回结果之前将geocoder.geocode函数视为立即完成。真正发生的是geocoder.geocode被触发,然后你立即返回结果。由于异步结果很可能未返回,因此结果为空。将地理编码结果视为推动而不是拉动。 storeResult函数(未显示)是您需要执行的任何代码以保存信息。由于您将结果与错误字符串组合在一起,因此必须在storeResult函数中处理该错误字符串。作为替代方案,您可以在结果中指定成功或失败的状态。

The problem you're facing is that you're treating the geocoder.geocode function as immediately completing before you do the return result. What's really happening is that the geocoder.geocode is triggered, then you get an immediate return of result. Because the asynchronous result has most likely not returned, your result is empty. Think of the geocoding result as a push, not a pull. The storeResult function, not shown, is whatever code you need to do to save the information. Because you're combining a result with an error string, you have to handle that in your storeResult function. As an alternative, you can have a status in the result that indicates succcess or failure.

function getLatLong(address) {
var geocoder = new google.maps.Geocoder();
var result = "";
geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
         result[lat] = results[0].geometry.location.Pa;
         result[lng] = results[0].geometry.location.Qa;
     } else {
         result = "Unable to find address: " + status;
     }
     storeResult(result);
    });
}

这篇关于使用google.maps.geocoder检索位置的纬度/经度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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