Cordova Geolocation plugin returning empty position object on Android

后端 未结 3 670
感情败类
感情败类 2021-01-12 07:52

I\'ve had quite some issues with the Geolocation Cordova plugin (org.apache.cordova.geolocation). It works fine on iOS, but it doesn\'t at all on Android.

As I under

相关标签:
3条回答
  • 2021-01-12 08:03

    The Geolocation object passed to the callbacks in navigator.geolocation.getCurrentLocation() contains two prototype getters coords and timestamp, which means that hasOwnProperty will return false, which I assume that JSON.stringify excludes.

    When logging all keys on the object I get the following:

    [object Geoposition]
      .coords [object Coordinates]
         .latitude
         .longitude
         .altitude
         .accuracy 
         .altitudeAccuracy
         .heading
         .speed
      .timestamp
    

    Never the less, these values are valid when accessed normally.

    0 讨论(0)
  • 2021-01-12 08:26

    OK, after a long long time of debugging, I found the problem. Apparently, the getCurrentPosition() function returns a 'special' object in Android, which evaluates to {} when using JSON.stringify(). If I outputted the raw return object to the console, it turned out it wasn't empty at all.

    So, following ridiculous adjustments fixed my code:

    navigator.geolocation.getCurrentPosition(function (position) {
        var positionObject = {};
    
        if ('coords' in position) {
            positionObject.coords = {};
    
            if ('latitude' in position.coords) {
                positionObject.coords.latitude = position.coords.latitude;
            }
            if ('longitude' in position.coords) {
                positionObject.coords.longitude = position.coords.longitude;
            }
            if ('accuracy' in position.coords) {
                positionObject.coords.accuracy = position.coords.accuracy;
            }
            if ('altitude' in position.coords) {
                positionObject.coords.altitude = position.coords.altitude;
            }
            if ('altitudeAccuracy' in position.coords) {
                positionObject.coords.altitudeAccuracy = position.coords.altitudeAccuracy;
            }
            if ('heading' in position.coords) {
                positionObject.coords.heading = position.coords.heading;
            }
            if ('speed' in position.coords) {
                positionObject.coords.speed = position.coords.speed;
            }
        }
    
        if ('timestamp' in position) {
            positionObject.timestamp = position.timestamp;
        }
    
        // Use the positionObject instead of the position 'object'
        alert(JSON.stringify(positionObject));            
    }
    

    iOS works fine without above adjustments, but as my app is a Phonegap application, I always apply the above.

    0 讨论(0)
  • 2021-01-12 08:29

    With Angular, you can fix this with :

    location = angular.copy(location)
    
    0 讨论(0)
提交回复
热议问题