如何使用Cordova Geolocation API进行反向地理编码以获得城市和国家?

dea*_*hot 4 javascript geolocation reverse-geocoding cordova hybrid-mobile-app

我正在构建一个混合移动应用程序,使用英特尔的App Framework进行用户界面和Cordova访问本机设备功能.

作为开发的一部分,我需要获取用户的位置(城市和国家)并在文本框中显示它.

通过使用下面的代码,我可以获得纬度和经度并将其显示在两个不同的文本框中(分别具有ID纬度和经度).如何将纬度和经度转换为城市和乡村.

  function Geolocation() {
                    var onSuccess = function(position) {
                        document.getElementById('latitude').value = position.coords.latitude;
                        document.getElementById('longitude').value = position.coords.longitude;                    
                    };
                    var onFail = function() {
                        navigator.notification.alert('Cannot get the location');
                    };
                    navigator.geolocation.getCurrentPosition(onSuccess, onFail, {maximumAge:0, timeout:5000, enableHighAccuracy: true});
                }  
Run Code Online (Sandbox Code Playgroud)

注意 - 除了Cordova的Geolocation之外,我不使用任何其他插件来处理我的应用程序中的位置服务.这是一个混合应用程序,但目前我正在使用Android版本的应用程序.

Sér*_*pes 9

这被称为反向地理编码,有许多服务可以做到这一点 - 例如.谷歌地图,OpenStreetMaps等等.

我喜欢OpenStreetMaps,因为它容易做到.只是一个JSONP回调:

http://nominatim.openstreetmap.org/reverse?lat=-23.5880894&lon=-46.6321951&format=json&json_callback=my_callback

因此,您只需向此URL发出Ajax请求即可获得所需的值.例如:

function showCountry(lat, lon) {
    $.getJSON('//nominatim.openstreetmap.org/reverse?json_callback=?&format=json', {lat: lat, lon: lon}, function(data) {
       alert(data.address.country);
   });
}
Run Code Online (Sandbox Code Playgroud)