从地名获取位置纬度和经度值

Get location lattitude and longitude value from place name

本文关键字:经度 纬度 位置 获取      更新时间:2023-09-26

我正在编写一个JavaScript函数来返回给定地名的纬度和经度值。我使用谷歌地图API来获得结果。然而,我没有得到我想要的结果。下面是我的代码来获得结果。

function getLocationCoordinates(place)
{    
    var geocoder = new google.maps.Geocoder();
    var address = place;
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        //alert(results[0].geometry.location.H+","+results[0].geometry.location.L);
       return results[0].geometry.location.H+","+results[0].geometry.location.L;      
    } else {
        return "0,0";
    }
    });
} 

当我调用函数getLocationCoordinates('kollam')时,我得到值"未定义"。它应该返回值'8.8800,76.6000'。然而,当我警告'results[0].geometry.location. h +","+results[0].geometry.location. h +"。L'表示正确的值。如何使这个函数返回正确的值

你的代码有两个问题

首先geocoder.geocode()是异步的,这意味着你将无法返回响应到你的外部函数,因为在函数完成之前数据不会从谷歌服务器返回。

第二……即使它不是异步的,来自geocode回调内部的return也不会返回到外部函数。

目前getLocationCoordinates()将总是返回undefined,因为没有返回任何

您需要返回一个承诺,该承诺将与geocode响应一起解析,或者在geocode回调中使用数据。