Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am building a hybrid mobile application using Intel's App Framework for user interface and Cordova to access the native device functionalities.

As a part of the development, I need to get the user's location(City and Country) and show it in a text box.

By using the code below, I am able to get the Latitude and Longitude and show it in two different text boxes(with ID latitude and longitude respectively). How can I translate the latitude and longitude to City and Country.

  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});
                }  

Note - I don't use any other plugin other than Cordova's Geolocation to handle location services in my app. This is a hybrid app but currently I am working on the Android version of the app.

like image 505
deadshot Avatar asked Dec 25 '22 16:12

deadshot


1 Answers

This is called reverse geocoding are there are many services out there to do that - eg. Google Maps, OpenStreetMaps and many more.

I love OpenStreetMaps because it's very easy to do. Just a JSONP callback:

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

So you can just make an Ajax request to this URL and get the desired values. For example:

function showCountry(lat, lon) {
    $.getJSON('//nominatim.openstreetmap.org/reverse?json_callback=?&format=json', {lat: lat, lon: lon}, function(data) {
       alert(data.address.country);
   });
}
like image 94
Sérgio Lopes Avatar answered Jan 02 '23 00:01

Sérgio Lopes