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

How to do reverse geocoding with Cordova Geolocation API to get City and Country?

我正在构建混合移动应用程序,使用 Intel 的用户界面应用程序框架和 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});
                }  

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

这称为 反向地理编码 有很多服务可以做到这一点 - 例如。 Google 地图、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);
   });
}