Google地理编码,异步Javascript,不起作用 [英] Google Geocoding, Asynchronous Javascript, not working

查看:79
本文介绍了Google地理编码,异步Javascript,不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个外部.js文件中有一个函数,该文件应该采用地址字符串,然后返回纬度和经度.它什么也不返回.有人可以帮忙吗?

I have a function, in an external .js file which is supposed to take address string and then return latitude and longitude. It returns nothing. Can someone help please?

我也想问一下;在javascript中,当您从另一个函数中调用异步函数时;外部函数终止后,异步函数会终止吗?

I also would like to ask; in javascript, when you call an async function from within another function; does the async function terminate as soon as the outside function terminates?

这是代码,任何人都可以阐明为什么它不返回任何内容吗?谢谢.

Here is the code, could anyone shed light on why this does not return anything? Thanks.

function FindLatLong(address)
{
        var geocoder = new google.maps.Geocoder();

        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var lat = results[0].geometry.location.lat();
                var lng = results[0].geometry.location.lng();
                return { Status: "OK", Latitude: lat, Longitude: lng };
            }
        });
}

(我当然将google maps js lib放在顶部)

(I of course include the google maps js lib on top)

我基本上没有从地址解析器中获得好的结果;如果我不将其放在FindLatLong函数中,则可以使用相同的代码,而是将其嵌入在我调用FindLatLong的位置,即,将上面的代码放在FindLatLong函数中时不起作用,但是如果我将其用作调用javascript的一部分,则可以使用代码.函数会被调用,Geocoder()会被调用,但是不会返回"OK"结果,实际上不会返回任何结果,甚至不会出现来自Google的错误.

I basically do not get an OK result from geocoder; the same code works if I do not put it inside FindLatLong function, and instead just embed it in place where I call FindLatLong i.e. the code above does not work when put inside FindLatLong function, but works if I use it as part of the calling javascript code. The function does get called, Geocoder() does get called, but 'OK' result is not returned, in fact no result is resturned, not even error from google.

地址字符串是英国伦敦"

address string is "London, UK"

推荐答案

该方法是异步的,因此请使用回调!

The method is async, so use a callback!

function FindLatLong(address, callback)
{
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var lat = results[0].geometry.location.lat();
            var lng = results[0].geometry.location.lng();
            callback({ Status: "OK", Latitude: lat, Longitude: lng });
        }
    });
}

并调用函数:

FindLatLong(address, function(data) {
    console.log(data);
});

这篇关于Google地理编码,异步Javascript,不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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