Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Current Location using only GPS in Cordova/Phonegap

Tags:

html

cordova

I use the geolocation plugin in Cordova 3.5. And I have coded as follow:

navigator.geolocation.getCurrentPosition(function(pos) {
    var lat = pos.coords.latitude;
    var lng = pos.coords.longitude;
    alert("lat : "+lat+" lng : " +lng");
});

I am wandering whether this code can work to get lat lng without Internet connection and GPS on. If not, is there any solution to do so? Thank for your help.

like image 675
limmouyleng Avatar asked Jul 18 '14 09:07

limmouyleng


1 Answers

Without Internet connection, there are still sources like Cell ID's, RFID and MAC addresses of devices you are connected to (e. g. WIFI routers, Bluetooth)

The code should work, but you can add a few things (Eventlistener and error alert in case that the position cannot be found):

document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
            navigator.geolocation.getCurrentPosition(onSuccess, onError);
        }

    function onSuccess(pos) {
            var lat = pos.coords.latitude;
            var lng = pos.coords.longitude;
            alert("lat : " + lat + " lng : " + lng);

        }

    function onError(error) {
            alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
        }

I know that for example the Google location API uses a cache for the latest known location, which can be read out anytime. I am not sure if Cordova also uses something similar but it could be.

like image 130
ACB Avatar answered Sep 17 '22 04:09

ACB