如何做反向地理编码与Cordova地理定位API获得城市和国家

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

本文关键字:城市 国家 API Cordova 何做反 编码 定位      更新时间:2023-09-26

我正在构建一个混合移动应用程序,使用英特尔的应用程序框架作为用户界面和Cordova来访问本机设备功能。

作为开发的一部分,我需要得到用户的位置(城市和国家),并显示在一个文本框。

通过使用下面的代码,我能够获得纬度和经度,并将其显示在两个不同的文本框中(分别具有ID Latitude和Longitude)。如何将经纬度转换为城市和国家?

  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 Maps, OpenStreetMaps等等

我喜欢OpenStreetMaps,因为它非常容易做。只是一个JSONP回调:

http://nominatim.openstreetmap.org/reverse?lat= - 23.5880894,朗= -46.6321951,= json&amp格式;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);
   });
}