Giter Site home page Giter Site logo

apache / cordova-plugin-geolocation Goto Github PK

View Code? Open in Web Editor NEW
633.0 63.0 657.0 653 KB

Apache Cordova Geolocation Plugin

Home Page: https://cordova.apache.org/

License: Apache License 2.0

Java 8.36% JavaScript 60.70% Objective-C 30.94%
cordova library objective-c java nodejs javascript mobile android hacktoberfest ios

cordova-plugin-geolocation's Introduction

title description
Geolocation
Access GPS data.

cordova-plugin-geolocation

Android Testsuite Chrome Testsuite iOS Testsuite Lint Test

This plugin provides information about the device's location, such as latitude and longitude.

Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. There is no guarantee that the API returns the device's actual location.

To get a few ideas, check out the sample at the bottom of this page or go straight to the reference content.

This API is based on the W3C Geolocation API Specification.

WARNING: Collection and use of geolocation data raises important privacy issues. Your app's privacy policy should discuss how the app uses geolocation data, whether it is shared with any other parties, and the level of precision of the data (for example, coarse, fine, ZIP code level, etc.). Geolocation data is generally considered sensitive because it can reveal user's whereabouts and, if stored, the history of their travels. Therefore, in addition to the app's privacy policy, you should strongly consider providing a just-in-time notice before the app accesses geolocation data (if the device operating system doesn't do so already). That notice should provide the same information noted above, as well as obtaining the user's permission (e.g., by presenting choices for OK and No Thanks). For more information, please see the Privacy Guide.

This plugin defines a global navigator.geolocation object (for platforms where it is otherwise missing).

Although the object is in the global scope, features provided by this plugin are not available until after the deviceready event.

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        console.log("navigator.geolocation works well");
    }

Installation

This requires cordova 5.0+ ( current stable 1.0.0 )

cordova plugin add cordova-plugin-geolocation

Older versions of cordova can still install via the deprecated id ( stale 0.3.12 )

cordova plugin add org.apache.cordova.geolocation

It is also possible to install via repo url directly ( unstable )

cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git

Supported Platforms

  • Android (10.0.0 or later)
  • iOS (6.0.0 or later)

Methods

  • navigator.geolocation.getCurrentPosition
  • navigator.geolocation.watchPosition
  • navigator.geolocation.clearWatch

Objects (Read-Only)

  • Position
  • PositionError
  • Coordinates

navigator.geolocation.getCurrentPosition

Returns the device's current position to the geolocationSuccess callback with a Position object as the parameter. If there is an error, the geolocationError callback is passed a PositionError object.

navigator.geolocation.getCurrentPosition(geolocationSuccess,
                                         [geolocationError],
                                         [geolocationOptions]);

Parameters

  • geolocationSuccess: The callback that is passed the current position.

  • geolocationError: (Optional) The callback that executes if an error occurs.

  • geolocationOptions: (Optional) The geolocation options.

Example

    // onSuccess Callback
    // This method accepts a Position object, which contains the
    // current GPS coordinates
    //
    var onSuccess = function(position) {
        alert('Latitude: '          + position.coords.latitude          + '\n' +
              'Longitude: '         + position.coords.longitude         + '\n' +
              'Altitude: '          + position.coords.altitude          + '\n' +
              'Accuracy: '          + position.coords.accuracy          + '\n' +
              'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
              'Heading: '           + position.coords.heading           + '\n' +
              'Speed: '             + position.coords.speed             + '\n' +
              'Timestamp: '         + position.timestamp                + '\n');
    };

    // onError Callback receives a PositionError object
    //
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

iOS Quirks

Since iOS 10 it's mandatory to provide an usage description in the info.plist if trying to access privacy-sensitive data. When the system prompts the user to allow access, this usage description string will displayed as part of the permission dialog box, but if you didn't provide the usage description, the app will crash before showing the dialog. Also, Apple will reject apps that access private data but don't provide an usage description.

This plugins requires the following usage description:

  • NSLocationWhenInUseUsageDescription describes the reason that the app accesses the user's location, this is used while the app is running in the foreground.
  • NSLocationAlwaysAndWhenInUseUsageDescription describes the reason that the app is requesting access to the user’s location information at all times. Use this key if your iOS app accesses location information while running in the background and foreground.
  • NSLocationAlwaysUsageDescription describes the reason that the app is requesting access to the user's location at all times. Use this key if your app accesses location information in the background and you deploy to a target earlier than iOS 11. For iOS 11 and later, add both NSLocationAlwaysUsageDescription and NSLocationAlwaysAndWhenInUseUsageDescription to your app’s Info.plist file with the same message.

To add these entries into the info.plist, you can use the edit-config tag in the config.xml like this:

<edit-config target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
    <string>need location access to find things nearby</string>
</edit-config>
<edit-config target="NSLocationAlwaysAndWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
    <string>need location access to find things nearby</string>
</edit-config>
<edit-config target="NSLocationAlwaysUsageDescription" file="*-Info.plist" mode="merge">
    <string>need location access to find things nearby</string>
</edit-config>

Android Quirks

For historic reasons, this plugin requires GPS Hardware on Android devices, so your app will not be able to run on devices without. If you want to use this plugin in your app, but you do not require actual GPS Hardware on the device, install the plugin using the variable GPS_REQUIRED set to false:

cordova plugin add cordova-plugin-geolocation --variable GPS_REQUIRED="false"

If Geolocation service is turned off the onError callback is invoked after timeout interval (if specified). If timeout parameter is not specified then no callback is called.

navigator.geolocation.watchPosition

Returns the device's current position when a change in position is detected. When the device retrieves a new location, the geolocationSuccess callback executes with a Position object as the parameter. If there is an error, the geolocationError callback executes with a PositionError object as the parameter.

var watchId = navigator.geolocation.watchPosition(geolocationSuccess,
                                                  [geolocationError],
                                                  [geolocationOptions]);

Parameters

  • geolocationSuccess: The callback that is passed the current position.

  • geolocationError: (Optional) The callback that executes if an error occurs.

  • geolocationOptions: (Optional) The geolocation options.

Returns

  • String: returns a watch id that references the watch position interval. The watch id should be used with navigator.geolocation.clearWatch to stop watching for changes in position.

Example

    // onSuccess Callback
    //   This method accepts a `Position` object, which contains
    //   the current GPS coordinates
    //
    function onSuccess(position) {
        var element = document.getElementById('geolocation');
        element.innerHTML = 'Latitude: '  + position.coords.latitude      + '<br />' +
                            'Longitude: ' + position.coords.longitude     + '<br />' +
                            '<hr />'      + element.innerHTML;
    }

    // onError Callback receives a PositionError object
    //
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    // Options: throw an error if no update is received every 30 seconds.
    //
    var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });

geolocationOptions

Optional parameters to customize the retrieval of the geolocation Position.

{ maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };

Options

  • enableHighAccuracy: Provides a hint that the application needs the best possible results. By default, the device attempts to retrieve a Position using network-based methods. Setting this property to true tells the framework to use more accurate methods, such as satellite positioning. (Boolean)

  • timeout: The maximum length of time (milliseconds) that is allowed to pass from the call to navigator.geolocation.getCurrentPosition or geolocation.watchPosition until the corresponding geolocationSuccess callback executes. If the geolocationSuccess callback is not invoked within this time, the geolocationError callback is passed a PositionError.TIMEOUT error code. (Note that when used in conjunction with geolocation.watchPosition, the geolocationError callback could be called on an interval every timeout milliseconds!) (Number)

  • maximumAge: Accept a cached position whose age is no greater than the specified time in milliseconds. (Number)

Android Quirks

If Geolocation service is turned off the onError callback is invoked after timeout interval (if specified). If timeout parameter is not specified then no callback is called.

navigator.geolocation.clearWatch

Stop watching for changes to the device's location referenced by the watchID parameter.

navigator.geolocation.clearWatch(watchID);

Parameters

  • watchID: The id of the watchPosition interval to clear. (String)

Example

    // Options: watch for changes in position, and use the most
    // accurate position acquisition method available.
    //
    var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });

    // ...later on...

    navigator.geolocation.clearWatch(watchID);

Position

Contains Position coordinates and timestamp, created by the geolocation API.

Properties

  • coords: A set of geographic coordinates. (Coordinates)

  • timestamp: Creation timestamp for coords. (DOMTimeStamp)

Coordinates

A Coordinates object is attached to a Position object that is available to callback functions in requests for the current position. It contains a set of properties that describe the geographic coordinates of a position.

Properties

  • latitude: Latitude in decimal degrees. (Number)

  • longitude: Longitude in decimal degrees. (Number)

  • altitude: Height of the position in meters above the ellipsoid. (Number)

  • accuracy: Accuracy level of the latitude and longitude coordinates in meters. (Number)

  • altitudeAccuracy: Accuracy level of the altitude coordinate in meters. (Number)

  • heading: Direction of travel, specified in degrees counting clockwise relative to the true north. (Number)

  • speed: Current ground speed of the device, specified in meters per second. (Number)

Android Quirks

altitudeAccuracy: Not supported by Android devices, returning null.

PositionError

The PositionError object is passed to the geolocationError callback function when an error occurs with navigator.geolocation.

Properties

  • code: One of the predefined error codes listed below.

  • message: Error message describing the details of the error encountered.

Constants

  • PositionError.PERMISSION_DENIED
    • Returned when users do not allow the app to retrieve position information. This is dependent on the platform.
  • PositionError.POSITION_UNAVAILABLE
    • Returned when the device is unable to retrieve a position. In general, this means the device is not connected to a network or can't get a satellite fix.
  • PositionError.TIMEOUT
    • Returned when the device is unable to retrieve a position within the time specified by the timeout included in geolocationOptions. When used with navigator.geolocation.watchPosition, this error could be repeatedly passed to the geolocationError callback every timeout milliseconds.

Sample: Get the weather, find stores, and see photos of things nearby with Geolocation

Use this plugin to help users find things near them such as Groupon deals, houses for sale, movies playing, sports and entertainment events and more.

Here's a "cookbook" of ideas to get you started. In the snippets below, we'll show you some basic ways to add these features to your app.

Get your geolocation coordinates

function getWeatherLocation() {

    navigator.geolocation.getCurrentPosition
    (onWeatherSuccess, onWeatherError, { enableHighAccuracy: true });
}

Get the weather forecast

// Success callback for get geo coordinates

var onWeatherSuccess = function (position) {

    Latitude = position.coords.latitude;
    Longitude = position.coords.longitude;

    getWeather(Latitude, Longitude);
}

// Get weather by using coordinates

function getWeather(latitude, longitude) {

    // Get a free key at http://openweathermap.org/. Replace the "Your_Key_Here" string with that key.
    var OpenWeatherAppKey = "Your_Key_Here";

    var queryString =
      'http://api.openweathermap.org/data/2.5/weather?lat='
      + latitude + '&lon=' + longitude + '&appid=' + OpenWeatherAppKey + '&units=imperial';

    $.getJSON(queryString, function (results) {

        if (results.weather.length) {

            $.getJSON(queryString, function (results) {

                if (results.weather.length) {

                    $('#description').text(results.name);
                    $('#temp').text(results.main.temp);
                    $('#wind').text(results.wind.speed);
                    $('#humidity').text(results.main.humidity);
                    $('#visibility').text(results.weather[0].main);

                    var sunriseDate = new Date(results.sys.sunrise);
                    $('#sunrise').text(sunriseDate.toLocaleTimeString());

                    var sunsetDate = new Date(results.sys.sunrise);
                    $('#sunset').text(sunsetDate.toLocaleTimeString());
                }

            });
        }
    }).fail(function () {
        console.log("error getting location");
    });
}

// Error callback

function onWeatherError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

Receive updated weather forecasts as you drive around

// Watch your changing position

function watchWeatherPosition() {

    return navigator.geolocation.watchPosition
    (onWeatherWatchSuccess, onWeatherError, { enableHighAccuracy: true });
}

// Success callback for watching your changing position

var onWeatherWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        // Calls function we defined earlier.
        getWeather(updatedLatitude, updatedLongitude);
    }
}

See where you are on a map

Both Bing and Google have map services. We'll use Google's. You'll need a key but it's free if you're just trying things out.

Add a reference to the maps service.

 <script src="https://maps.googleapis.com/maps/api/js?key=Your_API_Key"></script>

Then, add code to use it.

var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getMapLocation() {

    navigator.geolocation.getCurrentPosition
    (onMapSuccess, onMapError, { enableHighAccuracy: true });
}

// Success callback for get geo coordinates

var onMapSuccess = function (position) {

    Latitude = position.coords.latitude;
    Longitude = position.coords.longitude;

    getMap(Latitude, Longitude);

}

// Get map by using coordinates

function getMap(latitude, longitude) {

    var mapOptions = {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map
    (document.getElementById("map"), mapOptions);


    var latLong = new google.maps.LatLng(latitude, longitude);

    var marker = new google.maps.Marker({
        position: latLong
    });

    marker.setMap(map);
    map.setZoom(15);
    map.setCenter(marker.getPosition());
}

// Success callback for watching your changing position

var onMapWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getMap(updatedLatitude, updatedLongitude);
    }
}

// Error callback

function onMapError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchMapPosition() {

    return navigator.geolocation.watchPosition
    (onMapWatchSuccess, onMapError, { enableHighAccuracy: true });
}

Find stores near you

You can use the same Google key for this.

Add a reference to the places service.

<script src=
"https://maps.googleapis.com/maps/api/js?key=Your_API_Key&libraries=places">
</script>

Then, add code to use it.

var Map;
var Infowindow;
var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getPlacesLocation() {
    navigator.geolocation.getCurrentPosition
    (onPlacesSuccess, onPlacesError, { enableHighAccuracy: true });
}

// Success callback for get geo coordinates

var onPlacesSuccess = function (position) {

    Latitude = position.coords.latitude;
    Longitude = position.coords.longitude;

    getPlaces(Latitude, Longitude);

}

// Get places by using coordinates

function getPlaces(latitude, longitude) {

    var latLong = new google.maps.LatLng(latitude, longitude);

    var mapOptions = {

        center: new google.maps.LatLng(latitude, longitude),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP

    };

    Map = new google.maps.Map(document.getElementById("places"), mapOptions);

    Infowindow = new google.maps.InfoWindow();

    var service = new google.maps.places.PlacesService(Map);
    service.nearbySearch({

        location: latLong,
        radius: 500,
        type: ['store']
    }, foundStoresCallback);

}

// Success callback for watching your changing position

var onPlacesWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getPlaces(updatedLatitude, updatedLongitude);
    }
}

// Success callback for locating stores in the area

function foundStoresCallback(results, status) {

    if (status === google.maps.places.PlacesServiceStatus.OK) {

        for (var i = 0; i < results.length; i++) {

            createMarker(results[i]);

        }
    }
}

// Place a pin for each store on the map

function createMarker(place) {

    var placeLoc = place.geometry.location;

    var marker = new google.maps.Marker({
        map: Map,
        position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function () {

        Infowindow.setContent(place.name);
        Infowindow.open(Map, this);

    });
}

// Error callback

function onPlacesError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchPlacesPosition() {

    return navigator.geolocation.watchPosition
    (onPlacesWatchSuccess, onPlacesError, { enableHighAccuracy: true });
}

See pictures of things around you

Digital photos can contain geo coordinates that identify where the picture was taken.

Use Flickr API's to find pictures that folks have taken near you. Like Google services, you'll need a key, but it's free if you just want to try things out.

var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getPicturesLocation() {

    navigator.geolocation.getCurrentPosition
    (onPicturesSuccess, onPicturesError, { enableHighAccuracy: true });

}

// Success callback for get geo coordinates

var onPicturesSuccess = function (position) {

    Latitude = position.coords.latitude;
    Longitude = position.coords.longitude;

    getPictures(Latitude, Longitude);
}

// Get pictures by using coordinates

function getPictures(latitude, longitude) {

    $('#pictures').empty();

    var queryString =
    "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=Your_API_Key&lat="
    + latitude + "&lon=" + longitude + "&format=json&jsoncallback=?";

    $.getJSON(queryString, function (results) {
        $.each(results.photos.photo, function (index, item) {

            var photoURL = "http://farm" + item.farm + ".static.flickr.com/" +
                item.server + "/" + item.id + "_" + item.secret + "_m.jpg";

            $('#pictures').append($("<img />").attr("src", photoURL));

           });
        }
    );
}

// Success callback for watching your changing position

var onPicturesWatchSuccess = function (position) {

    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getPictures(updatedLatitude, updatedLongitude);
    }
}

// Error callback

function onPicturesError(error) {

    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchPicturePosition() {

    return navigator.geolocation.watchPosition
    (onPicturesWatchSuccess, onPicturesError, { enableHighAccuracy: true });
}

cordova-plugin-geolocation's People

Contributors

agrieve avatar alsorokin avatar audreyso avatar bennmapes avatar breautek avatar clelland avatar cmarcelk avatar dblotsky avatar dpa99c avatar erisu avatar filmaj avatar hardeep avatar hermwong avatar infil00p avatar janpio avatar jcesarmobile avatar jlongster avatar ldeluca avatar macdonst avatar mmocny avatar normesta avatar purplecabbage avatar sarangan12 avatar sgrebnov avatar shazron avatar stacic avatar stevengill avatar timbru31 avatar vladimir-kotikov avatar zalun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-plugin-geolocation's Issues

Turning Location services on after timeout

Hi,

I am currently fixing some kinks with the geolocation in an application I am making.

As soon as the application boots, it calls the getCurrentLocation function.

I have noticed that if I open the application with location services disabled, then turn it on a few second after load, or after a TIMEOUT error, later calls of getCurrentLocation function do not work.

Typically I see that when I run the getCurrentLocation function, the GPS icon flashes in the statusbar of the phone, and the success method is executed. However, if a run the getCurrentLocation function after a TIMEOUT, or loading the application with location services off then turning them on later, the GPS icon does not appear and the error method is executed.

Does anyone have a solution to resolve this behavior?

Thanks

object(...) is not a function

When I use the get getCurrentPosition function of geoLocation, typescript gives the error Object(...) is not a function. I have recently(last 2 days) run into same issue when try to use the ionic-firebase and solved it by installing an older version of firebase.

Anyways, I know that this is version issue. Probably happening because of ionic team is slowly making it is way to ionic v4 completely. So Do you guys know what is the last version of ionic-geolocation that is compatible with ionic V3 app and how can I install it? I saw 0.3.12 in the README.md but it seems they recommend it for older version of cordova.

My current package versions :
Ts : ~2..6.2
Angular : ^5.2.11
Cordova : 7

Thanks in advance!

Position is retrieved only after reseting the GPS services.

Bug Report

Problem

Android:
When I am trying to retrieve the position for first time, just immediately after enabling location service it works - I get the position coords.
But when back again after some minutes or after changing position (20 km of change) and try again it doesn't work. It just gets timeout error when timeout is getting executed.
If you set 5 seconds or 30 seconds, no matter it just waiting until timeout and location is not getting retrieved. The "fix" for this issue is to completely turn of location services in the device and re open them and try again. Then after very very quick time, something like 300ms there a valid response with the position's coords.

iOS Xcode simulator (7, 8, 8s, iphonex etc...):
When using watchPosition, the position is getting retrieved first,
next beat after 5 seconds, there is an error of timeout. No matter what. Seems like Xcode simulator doesn't support the watchPosition interval. Is it?

What is expected to happen?

What does actually happen?

Information

Command or Code

let positionWatcher = navigator.geolocation.watchPosition(
  GeolocationSuccessCallback, // first time works
  GeolocationFailCallback, // second time, not works.
  {
    timeout: 10000, 
    enableHighAccuracy: true
  }
)

Environment, Platform, Device

Android Samsung Galaxy S7 device (not simulator).
Xcode's simulators - I have tried something like 5 or 6 iPhones versions.
iOS platform 9.0

Version information

Cordova: Cordova CLI, Cordova Platforms, Cordova Plugins
Other Frameworks: Ionic Framework and CLI version
Real device, Xcode etc.

Checklist

  • [x ] I searched for existing GitHub issues
  • [ x] I updated all Cordova tooling to most recent version
  • [x ] I included all the necessary information above

Rarely find position in Android

Bug Report

Problem

watchPosition is extremely rarely detects the position on real Android device while walking/driving/moving.

What is expected to happen?

To find the user's position even if he moves (walking/driving/cycling).

What does actually happen?

Timeout error in trying to get the position of the user. When the user is in office or doesn't moving the position is getting retrieved after 0.32 ms (very quick). But when the user moves with the device - nothing, changes are 1/20 that position will be found.

Information

You can try 20 times and maybe one of them will successfully find the position and return with a successful callback.
The rest of them will return fail callback with timeout error.

Command or Code

I have tested on real device on Android Samsung Galaxy S7 only so far.
I really hope this severe issue doesn't happening on iOS too..

Environment, Platform, Device

Android.

Version information

I don't know. Just my Samsung Galaxy S7.

Checklist

  • I searched for existing GitHub issues
  • I updated all Cordova tooling to most recent version
  • I included all the necessary information above

Android Error : Only secure origins are allowed error

Hi, the geolocation is not working on android, I always get the same message, using ionicdevapp + ionic serve -c and also ionic cordova run android on an android device, everything works well on IOS, some idea of how to solve the problem? I have read some forums but it is not clear to me if there is any solution.

Example code :

getPosition():any{
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};

this.geolocation.getCurrentPosition(options).then(response => {
  console.log('OK'); 
  

})
.catch(error =>{
  console.log("Error="+ error.code +" =>"+ error.message);
})
}

Error=1
Only secure origins are allowed (see: https ://goo.gl/Y0ZkNV).

Ionic:

ionic (Ionic CLI) : 4.2.1 (/usr/local/lib/node_modules/ionic)
Ionic Framework : ionic-angular 3.9.2
@ionic/app-scripts : 3.2.0

Cordova:

cordova (Cordova CLI) : 8.1.2 ([email protected])
Cordova Platforms : android 7.1.4
Cordova Plugins : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 2.2.5, (and 12 other plugins)

System:

Android SDK Tools : 26.1.1 (/usr/local/Android/Sdk/)
NodeJS : v8.10.0 (/usr/bin/node)
npm : not installed
OS : Linux 4.15

Can not get location

Issue Type

  • [ X] Bug Report

Description

Plugin can not get location even if everything is enabled in system. Android Xiaomi MI 6
, android 8.0.0 OPR1.170623.027

navigator.geolocation.getCurrentPosition always got Timeout expired on iOS simulator

Hi, the geolocation is not working on ios simulator, I always get the same Timeout expired message, and my code is very simple as following, and it works fine in Chrome , Safari browsers and also Android simulator.

self.handleGetLoc = function() { navigator.geolocation.getCurrentPosition( function(position) { alert('Latitude: ' + position.coords.latitude + '\n' + 'Longitude: ' + position.coords.longitude + '\n'); }, function(error) { console.log('code: ' + error.code + '\n' + 'message: ' + error.message + '\n’); }, {enableHighAccuracy: true, timeout: 2000, maximumAge: 1000, accuracy:10}); };

And it keep printing:
code: 3 message: Timeout expired

Relevant component versions:
"cordova-ios": "4.5.5",
"cordova-plugin-file": "6.0.1",
"cordova-plugin-geolocation": "4.0.1",
"cordova-plugin-whitelist": "^1.3.3"

ios simulator: iPhone 6 or iPhone X, and all others.
ios :12.1

In-app prompt to open location services and authorizations

Feature Request

Motivation Behind Feature

Why to use so many different parties plugins if those missions are neccassary anyway?

Feature Description

I would like to pop the GPS location services in app - without linking the user to the device's settings. This is not easy to tell him how to do that. And there he could potentially allow "Device only" location mode. This is not what I need. I want him to enable "High accuracy".
Now to tell the user to do this - this is not a good behaviour - this should be done by the app itself.

Alternatives or Workarounds

Installed a plugin that sends the user to do the job that the app supposed to do.

No Types

This plugin is missing the type definitions we usually have for TypeScript users.

iOS watchPosition problem

Bug Report

Problem

The function in subscribe in watchPosition is not called when the user does not touch the screen (or interact with the application) even if the position has changed

What is expected to happen?

Every time when the position has changed the function should be called.

What does actually happen?

When subscribing to the watchPosition the event function is first called 2-3 times. Then during the application stay in the foreground the event function is not called. There are no errors.

When the user touch the screen (sometimes) the function is called. Every time when the application goes to background and return to the foreground the function is called.

Information

Command or Code

Environment, Platform, Device

iOS 12.1

Version information

Ionic:

ionic (Ionic CLI) : 4.12.0 (/usr/local/lib/node_modules/ionic)
Ionic Framework : @ionic/angular 4.2.0
@angular-devkit/build-angular : 0.13.8
@angular-devkit/schematics : 7.2.4
@angular/cli : 7.3.8
@ionic/angular-toolkit : 1.4.1

Cordova:

cordova (Cordova CLI) : 9.0.0 ([email protected])
Cordova Platforms : ios 5.0.0
Cordova Plugins : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 3.1.2, (and 5 other plugins)

System:

Android SDK Tools : 25.2.5 (/Applications/android-sdks)
ios-sim : 7.0.0
NodeJS : v10.15.3 (/usr/local/bin/node)
npm : 6.9.0
OS : macOS Mojave
Xcode : Xcode 10.2 Build version 10E125

Code written in Ionic 4.

this.watch = this.geolocation.watchPosition();
this.watch.subscribe(
            (data) => {
                console.log("In watchPosition");
                console.log(data);
                this.data = data;
            },
            (error) => {
                console.log('Error watching location', error)
            }, 
            {
                maximumAge: 3000,
                timeout: 1000,
                enableHighAccuracy: true
            }
        );

Checklist

  • I searched for existing GitHub issues
  • I updated all Cordova tooling to most recent version
  • I included all the necessary information above

TypeError: Cannot read property 'getCurrentPosition' of undefined

Bug Report

What is expected to happen?

I wanted to get the data

What does actually happen?

Error in Success callbackId: Geolocation1100061559 : TypeError: Cannot read property 'getCurrentPosition' of undefined
 
processMessage failed: Error: TypeError: Cannot read property 'getCurrentPosition' of undefined
 
processMessage failed: Stack: TypeError: Cannot read property 'getCurrentPosition' of undefined
at win (./plugins/cordova-plugin-geolocation/www/android/geolocation.js:35:16)
at Object.callbackFromNative (./cordova.js:291:58)
at processAndroidEvent (./cordova.js:986:17)
at _class.<anonymous> (./cordova.js:1005:9)
at ./node_modules/tabris/tabris.min.js:1:27083
at _class.trigger (./node_modules/tabris/tabris.min.js:1:27247)
at _class.$trigger (./node_modules/tabris/tabris.min.js:1:63505)
at _class._trigger (./node_modules/tabris/tabris.min.js:1:63275)
at Tabris._notify (./node_modules/tabris/tabris.min.js:1:70355)
 
processMessage failed: Message: S01 Geolocation1100061559 sOK

Information

Code

 navigator.geolocation.getCurrentPosition(position => console.log(position), e => console.error(e));

console.log(navigator.geolocation); returns the following

{ getCurrentPosition: [Function: getCurrentPosition],
watchPosition: [Function: watchPosition],
clearWatch: [Function: clearWatch] }

Version information

Cordova: Cordova 8.1.2, cordova-plugin-geolocation - master branch
Other Frameworks: Tabris.js 3.0.0
Android 8.1.0

Checklist

  • I searched for existing GitHub issues
  • I updated all Cordova tooling to most recent version
  • I included all the necessary information above

Unhandled Promise rejection: Cannot read property '_privateInitialize' of undefined ;

Why is this happens whats the issue?

Unhandled Promise rejection: Cannot read property '_privateInitialize' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property '_privateInitialize' of undefined
    at Map.<anonymous> (Map.js:1415)
    at commandQueueExecutor.js:63
    at t.invoke (polyfills.js:3)
    at r.run (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)
    at o (polyfills.js:3) TypeError: Cannot read property '_privateInitialize' of undefined
    at Map.<anonymous> (http://localhost:8080/plugins/cordova-plugin-googlemaps/www/Map.js:1415:12)
    at http://localhost:8080/plugins/cordova-plugin-googlemaps/www/commandQueueExecutor.js:63:21
    at t.invoke (http://localhost:8080/build/polyfills.js:3:14976)
    at r.run (http://localhost:8080/build/polyfills.js:3:10143)
    at http://localhost:8080/build/polyfills.js:3:20242
    at t.invokeTask (http://localhost:8080/build/polyfills.js:3:15660)
    at r.runTask (http://localhost:8080/build/polyfills.js:3:10834)
    at o (http://localhost:8080/build/polyfills.js:3:7894)
n.onUnhandledError @ polyfills.js:3
r @ polyfills.js:3
(anonymous) @ polyfills.js:3
n.microtaskDrainDone @ polyfills.js:3
o @ polyfills.js:3
Promise.then (async)
r @ polyfills.js:3
t.scheduleTask @ polyfills.js:3
r.scheduleTask @ polyfills.js:3
r.scheduleMicroTask @ polyfills.js:3
f @ polyfills.js:3
t.then @ polyfills.js:3
nextTick @ Common.js:6
commandQueue.push.args @ commandQueueExecutor.js:62
callbackFromNative @ cordova.js:291
(anonymous) @ VM312:1

ERROR TypeError: Object(...) is not a function

ERROR TypeError: Object(...) is not a function
    at Geolocation.getCurrentPosition (index.js:28)
    at SurveyFormPage.webpackJsonp.257.SurveyFormPage.showPopup (survey-form.ts:59)
    at Object.eval [as handleEvent] (SurveyFormPage.html:16)
    at handleEvent (core.js:13589)
    at callWithDebugContext (core.js:15098)
    at Object.debugHandleEvent [as handleEvent] (core.js:14685)
    at dispatchEvent (core.js:10004)
    at core.js:10629
    at HTMLButtonElement.<anonymous> (platform-browser.js:2628)
    at t.invokeTask (polyfills.js:3)
View_SurveyFormPage_0 @ SurveyFormPage.html:16
proxyClass @ compiler.js:14659
DebugContext_.logError @ core.js:15038
ErrorHandler.handleError @ core.js:1510
IonicErrorHandler.handleError @ ionic-error-handler.js:61
dispatchEvent @ core.js:10008
(anonymous) @ core.js:10629
(anonymous) @ platform-browser.js:2628
t.invokeTask @ polyfills.js:3
onInvokeTask @ core.js:4751
t.invokeTask @ polyfills.js:3
r.runTask @ polyfills.js:3
e.invokeTask @ polyfills.js:3
p @ polyfills.js:2
v @ polyfills.js:2

Work on background

Feature Request

Motivation Behind Feature

Sometimes getting the position when app is on background is crucial.

Feature Description

Get the position on background.

Alternatives or Workarounds

Tried to make the app available on background using a plugin but this is not working and not a good behaviour at all.
The GPS should be working on background as well.

Fix NSLocationWhenInUseUsageDescription documentation (ios12+ config.xml)

Guys for Phonegap users, in config.xml fix the documentation, they should add the platform="ios" to the code, like this:

<edit-config  platform="ios"  target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
    <string>need location access to find things nearby</string>
</edit-config>

instead of


<edit-config   target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
    <string>need location access to find things nearby</string>
</edit-config>

NOT ABLE TO INSTALL PLUGIN

When I am trying to install the plugin I am getting this error previously it was working fine :

Installing "cordova-plugin-geolocation" for android
Failed to install 'cordova-plugin-geolocation': Error: ENOENT: no such file or directory, open '/var/www/html/WHATSUPLIFE/test/platforms/android/AndroidManifest.xml'
    at Object.openSync (fs.js:434:3)
    at Object.readFileSync (fs.js:339:35)
    at Object.parseElementtreeSync (/var/www/html/WHATSUPLIFE/test/platforms/android/cordova/node_modules/cordova-common/src/util/xml-helpers.js:180:27)
    at new AndroidManifest (/var/www/html/WHATSUPLIFE/test/platforms/android/cordova/lib/AndroidManifest.js:29:20)
    at AndroidProject.getPackageName (/var/www/html/WHATSUPLIFE/test/platforms/android/cordova/lib/AndroidProject.js:99:12)
    at Api.addPlugin (/var/www/html/WHATSUPLIFE/test/platforms/android/cordova/Api.js:223:57)
    at handleInstall (/home/webdior/.nvm/versions/node/v10.9.0/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:594:10)
    at /home/webdior/.nvm/versions/node/v10.9.0/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:357:28
    at _fulfilled (/home/webdior/.nvm/versions/node/v10.9.0/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/q/q.js:787:54)
    at /home/webdior/.nvm/versions/node/v10.9.0/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/q/q.js:816:30
(node:14997) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open '/var/www/html/WHATSUPLIFE/test/platforms/android/AndroidManifest.xml'
    at Object.openSync (fs.js:434:3)
    at Object.readFileSync (fs.js:339:35)
    at Object.parseElementtreeSync (/var/www/html/WHATSUPLIFE/test/platforms/android/cordova/node_modules/cordova-common/src/util/xml-helpers.js:180:27)
    at new AndroidManifest (/var/www/html/WHATSUPLIFE/test/platforms/android/cordova/lib/AndroidManifest.js:29:20)
    at AndroidProject.getPackageName (/var/www/html/WHATSUPLIFE/test/platforms/android/cordova/lib/AndroidProject.js:99:12)
    at Api.addPlugin (/var/www/html/WHATSUPLIFE/test/platforms/android/cordova/Api.js:223:57)
    at handleInstall (/home/webdior/.nvm/versions/node/v10.9.0/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:594:10)
    at /home/webdior/.nvm/versions/node/v10.9.0/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:357:28
    at _fulfilled (/home/webdior/.nvm/versions/node/v10.9.0/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/q/q.js:787:54)
    at /home/webdior/.nvm/versions/node/v10.9.0/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/q/q.js:816:30
(node:14997) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14997) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Any help is appreciated.

once user denied permission to track location, then it's not requesting permissions

 this.geo.getCurrentPosition(options).then((success)=>{
      this.lat=success.coords.latitude;
      this.lng=success.coords.longitude;
      window.alert("done");
    });
    }).catch((e)=>{
      console.log("failed");
      console.log(e);
}

I really don't understand why it's not requesting permission to user after once user disallow permission at first time....

how can I solve problem?

Offline Mode

Is this plugin works offline (Without Internet)?

If yes then how to force the plugin to run offline (Without Internet)?

My code is not working Offline, I just copied the docs code below.

this.geolocation.getCurrentPosition().then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
}).catch((error) => {
console.log('Error getting location', error);
});

Denying Android location permission triggers pause/resume cycle

Hi,

The geolocation plugin triggers a pause and resume event when you deny the location permission multiple time and then tick "Do not ask me again". This doesn't happen if you remove cordova-plugin-geolocation but the permission is not requested.

I would not expect these events to be triggered all the time, as it can have some annoying side effects in the application.

Example: we use an interval to manually request a new location every few seconds when using the app, geolocation.getCurrentPosition is called when the timer is fired, which can actually happen when the app is in background (I'm thinking to ask more about this on the cordova-android repo as this is unexpected). Generally not a problem, however with cordova-plugin-geolocation triggering its own resume event when the app is in the background, the app is re-opened automatically. We're looking at changing the implementation to manually stop all timeout and interval when the app is paused, which will fix the issue, however I think it's worth looking into cordova-plugin-geolocation to fix or document this behaviour.

POC

cordova create test-geolocation && cd test-geolocation
cordova platform add android
corvova plugin add cordova-plugin-geolocation

Replace www/index.html with the one provided

<!DOCTYPE html>
<html>

<head>
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <title>Hello World</title>

    <style>
        #log {height: 300px;overflow-x:auto;font-family: monospace;font-size: 12px;margin: 10px;padding:10px;border: 1px solid #999;text-transform:none;}
        #log div {padding: 3px 0;border-bottom: 1px solid #ccc;}
    </style>
</head>

<body>
    <div>
        <h1>Geolocation background test</h1>

        <button onclick="$log.innerHTML = '';" style="float: right;">clear log</button>

        <button onclick="request()">request()</button>
        <br>
        <div id="log"></div>

    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script>
        document.addEventListener('resume', () => log('event received: resume'));
        document.addEventListener('pause', () => log('event received: pause'));

        function request() {
            log('geolocation.getCurrentPosition()');
            navigator.geolocation.getCurrentPosition(
                (res) => log('geolocation response  -  ' + JSON.stringify(res)),
                (err) => log('geolocation error' + JSON.stringify(err)));
        }

        // in-page logging
        const $log = document.getElementById('log');
        function log(...args) {
            args.map(function (line) {
                const div = document.createElement('div');
                div.innerText = new Date().toISOString().replace(/^.+T/g, '') + ' - ' + line;
                $log.prepend(div);
            });
            console.log.apply(console, args);
        };

    </script>
</body>

</html>

Run on a device (I have not tested with an emulator) cordova run android --device. Tap on the "request" button, then deny the permission, check "do not ask again" and keep tapping on "request()" you will be able to see "pause" and "resume" events around the geolocation error callback.

Confirmed on a Samsun Galaxy S7 running Android 7.0, and a OnePlus 6T running Android 9.0.11, and a few customers had the same issue too.

If you want to trigger the app taking focus of the screen, redo the steps totick "do not ask again", add setTimeout(() => request(), 10000) and go back to the homescreen. The app will reappear automatically after 10 seconds.

ADB logs

01-16 14:25:19.572 26914 26914 I chromium: [INFO:CONSOLE(48)] "geolocation.getCurrentPosition()", source: file:///android_asset/www/index.html (48)
01-16 14:25:19.652 26914 26914 I chromium: [INFO:CONSOLE(48)] "event received: pause", source: file:///android_asset/www/index.html (48)
01-16 14:25:19.785 26914 26914 I chromium: [INFO:CONSOLE(48)] "geolocation error{"code":1,"message":"Illegal Access"}", source: file:///android_asset/www/index.html (48)
01-16 14:25:19.786 26914 26914 I chromium: [INFO:CONSOLE(48)] "event received: resume", source: file:///android_asset/www/index.html (48)

Askin permission when need

Iam using this plugin with this permission

how to ask permission when we need only.

In my situation it ask location when app initally load

Android app crashes while watching for location updates when app-based permission to access location is revoked.

The following issue occurs on Android v6.0 or higher in any app with cordova-plugin-geolocation:

  1. The app is started for the fist time and the user grants access to device's location.
  2. In the code a geolocation watch is started via
    navigator.geolocation.watchPosition(geolocationSuccess, geolocationError, geolocationOptions);
  3. While the watch is running and receiving location updates the user revokes app permissions to access the device's location in Android settings.
  4. The app immediately crashes without calling geolocationError callback or throwing any other error notice.

Cordova platform: android 7.1.1
cordova-plugin-geolocation version: 4.0.1

PositionError fails to fire on firefox when "Don't Allow" is pressed & "Remember this decision" isn't checked

Bug Report

PositionError fails to fire on firefox when "Don't Allow" is pressed & "Remember this decision" isn't checked

Problem

What is expected to happen?

PositionError should fire with a status of 1. "User denied geolocation prompt" when Don't Allow is pressed regardless of "remember this decision" being checked or not.

What does actually happen?

No success or error is error sent.

Information

Gif of issue below
9FF87977-9C9A-4F9F-A192-FF689AC7827A

Command or Code

Environment, Platform, Device

Windows - Laptop - Firefox v65.0.2

Version information

Ionic Framework - cordova-plugin-geolocation v^4.0.1"

Checklist

  • I searched for existing GitHub issues
  • I updated all Cordova tooling to most recent version
  • I included all the necessary information above

Documentation for gelocation plugin should be updated to meet new apple rules about location access

Feature Request

Motivation Behind Feature

Apple identified some issues without specified NSLocationAlwaysUsageDescription in info,plist, so the documentation for geolocation plugin is missed some informations, please update the documentation and add these rules to it:

edit-config target="NSLocationAlwaysAndWhenInUseUsageDescription" file="-Info.plist" mode="merge">
string>Need location access to find things nearby. /string>
/edit-config>
edit-config target="NSLocationWhenInUseUsageDescription" file="
-Info.plist" mode="merge">
string>Need location access to find things nearby. /string>
/edit-config>
edit-config target="NSLocationAlwaysUsageDescription" file="*-Info.plist" mode="merge">
string>Need location access to find things nearby./string>
/edit-config>

(*** please note that i removed the start of codes because github not allowed these, so please add < in the first of each code)

Apple will send an email about issues found if you don't add the previous rules to info.plist.

Message from apple:
Missing Purpose String in Info.plist File - Your app's code references one or more APIs that access sensitive user data. The app's Info.plist file should contain a NSLocationAlwaysUsageDescription key with a user-facing purpose string explaining clearly and completely why your app needs the data. Starting Spring 2019, all apps submitted to the App Store that access user data will be required to include a purpose string. If you're using external libraries or SDKs, they may reference APIs that require a purpose string. While your app might not use these APIs, a purpose string is still required. You can contact the developer of the library or SDK and request they release a version of their code that doesn't contain the APIs. Learn more (https://developer.apple.com/documentation/uikit/core_app/protecting_the_user_s_privacy).

Feature Description

Please add these rules to the documentation:
/edit-config target="NSLocationAlwaysAndWhenInUseUsageDescription" file="-Info.plist" mode="merge">
string>Need location access to find things nearby. /string>
/edit-config>
edit-config target="NSLocationWhenInUseUsageDescription" file="
-Info.plist" mode="merge">
string>Need location access to find things nearby. /string>
/edit-config>
edit-config target="NSLocationAlwaysUsageDescription" file="*-Info.plist" mode="merge">
string>Need location access to find things nearby./string>
/edit-config>

(*** please note that i removed the start of codes because github not allowed these, so please add < in the first of each code)

Alternatives or Workarounds

Geolocation - Error getting location Only secure origins are allowed

Bug Report

Problem

What does actually happen?

this.geolocation.getCurrentPosition().then(response => {
console.log(response);
}).catch((error) => {
console.log('Error getting location', error.message);
alert(error);
});

I got the error: this.geolocation.getCurrentPosition().then(response => {
console.log(response);
}).catch((error) => {
console.log('Error getting location', error.message);
alert(error);
});

And appears in alert Android: [object PositionErro]

Information

Command or Code

Environment, Platform, Device

Version information

Ionic:

ionic (Ionic CLI) : 4.12.0 (C:\Users\Bonny\AppData\Roaming\npm\node_modules\ionic)
Ionic Framework : ionic-angular 3.9.2
@ionic/app-scripts : 3.2.1

Cordova:

cordova (Cordova CLI) : 8.0.0
Cordova Platforms : android 7.0.0, browser 5.0.4, ios 4.5.5
Cordova Plugins : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 2.4.0, (and 15 other plugins)

System:

Android SDK Tools : 26.1.1 (C:\Users\Bonny\AppData\Local\Android\Sdk)
NodeJS : v11.12.0 (C:\Program Files\nodejs\node.exe)
npm : 6.4.1
OS : Windows 10

Checklist

  • I searched for existing GitHub issues
  • I updated all Cordova tooling to most recent version
  • I included all the necessary information above

Support for cordova-osx

Hi,
I am building an application for OSX using cordova-osx platform. However when I try to get geolocation coordinates. I am getting an error
code : 1
message : User denied Geolocation

I however feel that through this plugin with wrapper around CoreLocation APIs can solve the problem.

Thank you in advance

Tests fail in "local" iOS 10.0

For some reason tests fail when run on a local (non Saucelabs) emulator via Paramedic: https://travis-ci.org/apache/cordova-plugin-geolocation/jobs/547251753

**************************************************
*                    Failures                    *
**************************************************
1) cordova-plugin-geolocation-tests.tests >> getCurrentPosition method success callback geolocation.spec.6 should be called with a Position object
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. in file:///Users/travis/Library/Developer/CoreSimulator/Devices/62332DED-D4BB-47D1-AF47-E8BE8CF8D7BC/data/Containers/Bundle/Application/FE05FEAD-3977-46A3-9068-EEC2496D9245/HelloCordova.app/www/cdvtests/jasmine-2.4.1/jasmine.js (line 1909)
2) cordova-plugin-geolocation-tests.tests >> watchPosition method success callback geolocation.spec.8 should be called with a Position object
  - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. in file:///Users/travis/Library/Developer/CoreSimulator/Devices/62332DED-D4BB-47D1-AF47-E8BE8CF8D7BC/data/Containers/Bundle/Application/FE05FEAD-3977-46A3-9068-EEC2496D9245/HelloCordova.app/www/cdvtests/jasmine-2.4.1/jasmine.js (line 1909)

NSLocationAlwaysUsageDescription now mandatory?

It looks like the key NSLocationAlwaysUsageDescription is now mandatory, too. Should we document this?

This is the warning Apple sent after uploading the app:

"Missing Purpose String in Info.plist File. Your app's code references one or more APIs that access sensitive user data. The app's Info.plist file should contain a NSLocationAlwaysUsageDescription key with a user-facing purpose string explaining clearly and completely why your app needs the data. Starting spring 2019, all apps submitted to the App Store that access user data will be required to include a purpose string.If you're using external libraries or SDKs, they may reference APIs that require a purpose string. While your app might not use these APIs, a purpose string is still required. You can contact the developer of the library or SDK and request they release a version of their code that doesn't contain the APIs. Learn more (https://developer.apple.com/documentation/uikit/core_app/protecting_the_user_s_privacy)."

Location does not turn on

When the function gets called the app ask for permission to use location, but it does not turn on location even I press 'allow',
navigator.geolocation.getCurrentPosition(onSuccess, onError);

but it works when manually turn on location
Android 7.1.1
8.1.2 ([email protected])
Geolocation Plugin 4.0.1

screenshot_20181230-161111

Unable to obtain location information.

phone:nubia NX569H
android:6.0.1

The execution method console.log no information.

//定位
public getGPS(){
let that=this;
this.geolocation.getCurrentPosition().then((resp) => {
console.log(1,resp.coords.latitude,resp.coords.longitude);
}).catch((error) => {
console.log('Error getting location', error);
});

}

How to support background mode?

It seems this plugin doesn't support background mode, while testing in android8.1, while the app in background mode, this plugin can't record location info at all, is there anyone knows how to solve this?

Can't Take Android Build

 <plugin name="cordova-plugin-geolocation" spec="^4.0.1" />
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources
:app:createDebugCompatibleScreenManifests UP-TO-DATE
:app:processDebugManifest
:app:splitsDiscoveryTaskDebug UP-TO-DATE
:app:processDebugResources
:app:generateDebugSources
:app:javaPreCompileDebug
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
:app:compileDebugJavaWithJavac
:app:compileDebugNdk NO-SOURCE
:app:compileDebugSources
:CordovaLib:mergeDebugShaders UP-TO-DATE
:CordovaLib:compileDebugShaders UP-TO-DATE
:CordovaLib:generateDebugAssets UP-TO-DATE
:CordovaLib:mergeDebugAssets UP-TO-DATE
:app:mergeDebugShaders UP-TO-DATE
:app:compileDebugShaders UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets
:app:transformClassesWithStackFramesFixerForDebug
:app:transformClassesWithDesugarForDebug
java.lang.IllegalStateException: Dex archives: setting .DEX extension only for .CLASS files
        at com.google.common.base.Preconditions.checkState(Preconditions.java:456)
        at com.android.builder.dexing.ClassFileEntry.withDexExtension(ClassFileEntry.java:64)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.removeDeletedEntries(DexArchiveBuilderTransform.java:274)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.transform(DexArchiveBuilderTransform.java:241)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:222)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:218)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
        at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:213)
        at sun.reflect.GeneratedMethodAccessor257.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:60)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:128)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:46)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:311)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:202)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:132)
        at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:107)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
        at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
        at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
        at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:45)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:29)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:71)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:45)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:51)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:58)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:33)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
        at java.lang.Thread.run(Thread.java:748)


FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: java.lang.IllegalStateException: Dex archives: setting .DEX extension only for .CLASS files

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

:app:transformClassesWithDexBuilderForDebug FAILED
36 actionable tasks: 11 executed, 25 up-to-date
BUILD FAILED in 5s
Error: /Users/brt/Documents/Developement/ionic/Belafy/platforms/android/gradlew: Command failed with exit code 1 Error output:
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
java.lang.IllegalStateException: Dex archives: setting .DEX extension only for .CLASS files
        at com.google.common.base.Preconditions.checkState(Preconditions.java:456)
        at com.android.builder.dexing.ClassFileEntry.withDexExtension(ClassFileEntry.java:64)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.removeDeletedEntries(DexArchiveBuilderTransform.java:274)
        at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.transform(DexArchiveBuilderTransform.java:241)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:222)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:218)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
        at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:213)
        at sun.reflect.GeneratedMethodAccessor257.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:60)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:128)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:46)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:311)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:202)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:132)
        at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:107)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
        at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
        at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
        at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.D
[ERROR] An error occurred while running subprocess cordova.
        
        cordova build android exited with exit code 1.

Ionic Info:

Ionic:

   ionic (Ionic CLI)  : 4.1.0 (/usr/local/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.1.11

Cordova:

   cordova (Cordova CLI) : 7.0.0
   Cordova Platforms     : android 7.0.0
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.2, cordova-plugin-ionic-webview 2.0.3, (and 5 other plugins)

System:

   ios-deploy : 2.0.0
   NodeJS     : v10.8.0 (/usr/local/bin/node)
   npm        : 6.3.0
   OS         : macOS High Sierra
   Xcode      : Xcode 9.4.1 Build version 9F2000

Environment:

   ANDROID_HOME : not set

Phonegap Build Log: Plugin doesn't support this project's cordova-android version

I'm working on a phonegap project that needs to show the current position of the user. The plugin works fine when tested on a browser or on the PhoneGap App for Android, but when i build the apk for android on PhoneGap Build the function navigator.geolocation.getCurrentPosition runs the error function with:

Code: 2, Message: application does not have sufficient geolocation permissions.

And on the PhoneGap Build Log I see this, which kinda tells me something wrong is happening when installing the plugin in the apk.

PLUGIN OUTPUT
--------------------------------------------------------------------------------
Fetching plugin "cordova-plugin-geolocation@^4.0.1" via npm
Installing "cordova-plugin-geolocation" at "4.0.1" for android
Plugin doesn't support this project's cordova-android version. cordova-android: 6.1.2, failed version requirement: >=6.3.0
Skipping 'cordova-plugin-geolocation' for android

I thought that i just had to update the cordova-android version but when i run cordova platforms i get:

cordova platforms
Installed platforms:
  android 6.4.0
  browser 5.0.4
  ios 4.5.5
Available platforms:
  osx ~4.0.1
  windows ~6.0.0

So my cordova-android is actually different when i send it to the build.

Android location permissions not being requested using Cordova 9

Bug Report

Problem

I am trying out using Cordova 9, and most things seem to be working alright, but the geolocation plugin is not adding the appropriate uses-permission tags to the android manifest file.

Note: this works fine if I revert back cordova-cli@8 and cordova-android@7

What is expected to happen?

Adding cordova-plugin-geolocation should add the appropriate permissions to the manifest file and allow requesting location in the app.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

What does actually happen?

Adding cordova-plugin-geolocationdoes not add the appropriate permissions, and thus, my app is not able to request a GPS location.

Environment, Platform, Device

Android (have not attempted iOS yet)

Version information

I am using

"cordova-plugin-geolocation": "4.0.1"
"cordova-android": "^8.0.0"
"cordova": "^9.0.0"
"ionic": "4.12.0"

Checklist

  • [ x] I searched for existing GitHub issues
  • [x ] I updated all Cordova tooling to most recent version
  • [x ] I included all the necessary information above

Geocoder.geocode returns 'Request denied' status

navigator.geolocation.getCurrentPosition returns success but, geocoder.geocode returns status -'Request denied'

Code:
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(position) {
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode(
{ 'latLng': latlng },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//mycode
}

watchPosition on iphoneXR causes Cordova crash/restart

Bug Report

Using this code on an iPhone XR
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { maximumAge: 3, timeout: 5000, enableHighAccuracy: true });

ios version 12.2

NOTE: same code on other iphone devices (iphone 5SE, iphone 6S, iphone 7) does NOT cause the crash.

Causes what I believe to be a Cordova crash and restart. See ios analytics files (attached/included)

Problem

After about 2 minutes after starting up the watchPosition with the given parameters, the app appeared to crash. This information from the ios analytics file led me to watchPosition:
Event: wakeups
Action taken: none
Wakeups: 45001 wakeups over the last 211 seconds (213 wakeups per second average), exceeding limit of 150 wakeups per second over 300 seconds
Wakeups limit: 45000
Limit duration: 300s
Wakeups caused: 45001
Duration: 145.75s
Steps: 11

Suppressed the start of watchPosition and the app operated stable.

Command or Code

var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { maximumAge: 3, timeout: 5000, enableHighAccuracy: true });

Environment, Platform, Device

iphone XR (new on 5/2/19)

Version information

Phonegap version: CLI 7.1.0
Phonegap builder version: 2

Geolocation plugins tested: 2.4.3 and 4.0.1

Checklist

  • [X ] I searched for existing GitHub issues
  • [ X] I updated all Cordova tooling to most recent version
  • [ X

LTIS_OH_DEV.wakeups_resource-2019-05-09-092828.txt
LTIS_OH_DEV-2019-05-09-102418.txt

] I included all the necessary information above

ERROR in node_modules/@ionic-native/geolocation/index.d.ts(2,10): error TS2305: Module

ERROR in node_modules/@ionic-native/geolocation/index.d.ts(2,10): error TS2305: Module

I'm implementing in the app the lib but it gives this error

Ionic:

ionic (Ionic CLI) : 4.1.1 (/usr/lib/node_modules/ionic)
Ionic Framework : @ionic/angular 4.0.0-beta.3
@angular-devkit/core : 0.7.5
@angular-devkit/schematics : 0.7.5
@angular/cli : 6.1.5
@ionic/ng-toolkit : 1.0.7
@ionic/schematics-angular : 1.0.5

Cordova:

cordova (Cordova CLI) : 8.0.0
Cordova Platforms : none
Cordova Plugins : no whitelisted plugins (0 plugins total)

System:

Android SDK Tools : 26.1.1 (/home/eduardo/Android/Sdk)
NodeJS : v8.11.4 (/usr/bin/node)
npm : 6.4.1
OS : Linux 4.15

Emit position event only by the time that a distance change was made - not automatically after 5 seconds

Feature Request

Motivation Behind Feature

This is a must have feature. Save battery consuming, report about position changes to API only when there a significant change - instead of every 5 seconds.

Feature Description

The watchPosition method emits the success callback after every 5 seconds (if there no errors). This is bad. It has to emit the event only when the user actually moves - in order to save battery and report to remote APIs only when needed.

Alternatives or Workarounds

I am using some wrapper of the service, only when there some significant distance between previous position that was saved I send it to the DB.
I defined by my own the minimal distance in meters in order to consider a change.
This is not a good way of working. This plugin should emit only when there was a change in position and it should be setted for what is change in position or not.

Timeout on iOS after clearWatch

iOS 11.4.1

I experience a timeout error after calling watchPosition and then calling clearWatch in the first success callback.

Example code would be some thing like

var count = 0
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });

var onSuccess= function (position) {
  if (count === 0) {
    navigator.geolocation.clearWatch(watchID);
  }
  count ++;
}

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

What I believe is happening is

  1. watchPosition calls geolocation.getCurrentPosition followed by
  2. exec(win, fail, 'Geolocation', 'addWatch', [id, options.enableHighAccuracy]);
  3. The onSuccess callback following step 1 calls clearWatch
  4. The win callback following step 2 restarts the timeout
  5. The timeout is hit because the geolocation was stopped in step 3

This was unexpected behaviour which I only figured out by looking at the source code of the plugin. I could easily resolve the problem by calling clearWatch a second time but it would be nicer for the plugin to handle this.

Not working on Android devices

$ ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"
$ npm install --save @ionic-native/geolocation

I used the above plugin referred in
https://ionicframework.com/docs/native/geolocation/
But I am not getting the cureent location on android devices.Many people have the same issue

https://forum.ionicframework.com/t/ionic-get-current-location/118168/6
tried using running the app using prod flag dint help.

please help me

Android - Notification and icon when getting location

Hello.

In Android 8 only. I am getting a notification with an icon which isn't the icon of my App. Is it possible to change this icon and the texts or remove the notification?

I am calling the method to get my position like this:

this.geolocation.getCurrentPosition({ enableHighAccuracy: true, timeout: 1000, maximumAge: 1000 }).then(...

And this is the icon I am talking about (the one about fusedlocationprovider):

pic

Is there any way to do this?

Thanks!

Frequency/Interval feature for `watchPosition`

Hi,
Currently the plugin pulls updates every 1000ms (or 1s). Is there any intention to add frequency as a parameter?

(I can make a hack to ignore updates unless certain period had elapsed, but device will still drain the battery faster)

Thanks in advance,
Siege

How to track location in background on iOS?

This plugin works really well with on iOS. But I would like to use this plugin to track location even when the app is in the background on iOS. Is there any way to implement background location with this plugin on iOS? If yes, then is there any working examples available for this?

Geolocation Interval position

Is there any function available in the plugin that updates the position of the coordinates in a certain time interval or a range of meters traveled, or something similar?

Getting location with high accuracy taking time more than 4 mins

let getOptions = { enableHighAccuracy: true };
this.geolocation.getCurrentPosition(getOptions).then(position => {
//code to use location
});

Device : Nokia 6(Android Oreo), iPhone 6 (iOS 11)

version information
"cordova-plugin-geolocation": "^4.0.1",
"ionic-angular": "3.9.2",

Timestamp of getCurrentPosition wrong? (iOS 12)

Bug Report

Problem

When comparing the timestamps of the object returned by the geolocation plugin, we found that the timestamps are from before the call to the getCurrentPosition function.
We log

  • the time when we make the request to getCurrentPosition

  • the timestamp returned by the geolocation.

What is expected to happen?

The timestamp of the geolocation-object should be newer than the timestamp that we log before the call to the plugin is made.

What does actually happen?

The timestamp of the geolocation-object is most of the times (not consistently) older than the timestamp that we log before the call to the plugin is made.
Example:
Timestamp_Call - Timestamp_GPS
15:45:28.475 - 15:45:28.466

The question is: Is the timestamp wrong or does the plugin return a value coming from an older call to getCurrentPosition?

Information

Our options are:
timeout: Infinity,
maximumAge: 0,
enableHighAccuracy: true

I checked this on a trivial app containing no other plugins.
In the browser we observe the expected behaviour with the timestamp of the GPS position being slightly newer than the timestamp of the call.
Example:
Timestamp_Call - Timestamp_GPS
15:45:0.241 - 15:45:0.276

I deployed it via Xcode and ran it directly on the device.

Command or Code

App component:

import { Component, ViewChild } from '@angular/core';
import { Nav } from 'ionic-angular';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  @ViewChild(Nav) nav: Nav;

  private _timer;
  private readStartTimestamp;
  private log = [];

  ngOnInit() {
    this._startWatchingPosition();
}

  _getCurrentPosition() {
      this.readStartTimestamp = new Date();
      navigator.geolocation.getCurrentPosition((position) => {
        (<any>position).gpsStartTimestamp = this.formatDate(this.readStartTimestamp);
        (<any>position).gpsTimestamp = this.formatDate(new Date(position.timestamp));
        this.log.push(position);
      }, (err) => {
        console.log("Error getting current location: " + err.message);
      }, {
          timeout: Infinity,
          maximumAge: 0,
          enableHighAccuracy: true
      });
  }

  _startWatchingPosition() {
      clearInterval(this._timer);
      this._getCurrentPosition();
      this._timer = setInterval(() => {
        this._getCurrentPosition();
      }, 5000);
      console.log("Watching position started");
  };

  private formatDate(date: Date) {
    return date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + '.' + date.getMilliseconds();
  }
}

App template:

<ion-content>

  <h1>TESTAPP Geolocation Plugin</h1>
  <div style="padding: 10px;overflow: scroll; -webkit-overflow-scrolling: touch; user-select: text; -webkit-user-select: text" id="text">
      <ion-item *ngFor="let position of log.slice().reverse()">
          {{position.gpsStartTimestamp}} - {{position.gpsTimestamp}} - {{position.coords.longitude}} / {{position.coords.latitude}}
      </ion-item>
  </div>
</ion-content>

If necessary, I can provide a sample project, but it really only consists of these two files + bootstrapping.

cordova add platform ios
cordova prepare ios
Run with Xcode on iOS Device

Environment, Platform, Device

I tested it on iOS 12.1 (iPhone) and 12.3 (iPad), both showing the mentioned behaviour.
I didn't test it on Android.
The browser does not show the mentioned behaviour, but behaves as expected.

Version information

cordova platform ls
Installed platforms:
ios 5.0.1

cordova plugin ls
cordova-plugin-geolocation 4.0.1 "Geolocation"

cordova --version
9.0.0 ([email protected])

from package.json:

"cordova-ios": "5.0.1",
"cordova-plugin-geolocation": "4.0.1",
"ionic-angular": "3.9.6"

ionic --version
4.10.2

OSX 10.14.5
Xcode 10.2.1

Checklist

  • I searched for existing GitHub issues
  • I updated all Cordova tooling to most recent version
  • I included all the necessary information above

iOS CDVLocation.m error on Crashlytics

Issue Type

  • Bug Report
  • Feature Request
  • Support Question

Description

I'm getting errors registered on crashlytics for iOS. With occurrences on all the different devices (Iphone 6, 7,....)

Information

Fatal Exception: NSGenericException
0  CoreFoundation                 0x1832e2d8c __exceptionPreprocess
1  libobjc.A.dylib                0x18249c5ec objc_exception_throw
2  CoreFoundation                 0x1832e23c0 -[__NSSingleObjectEnumerator initWithObject:]
3  Garupa                         0x1030b4640 -[CDVLocation returnLocationError:withMessage:] (CDVLocation.m:312)
4  Garupa                         0x1030b3178 -[CDVLocation startLocation:] (CDVLocation.m:117)
5  Garupa                         0x1030b3a64 __27-[CDVLocation getLocation:]_block_invoke (CDVLocation.m:222)
6  libdispatch.dylib              0x182bd4aa0 _dispatch_call_block_and_release
7  libdispatch.dylib              0x182bd4a60 _dispatch_client_callout
8  libdispatch.dylib              0x182bdbb84 _dispatch_queue_override_invoke$VARIANT$mp
9  libdispatch.dylib              0x182be1cac _dispatch_root_queue_drain
10 libdispatch.dylib              0x182be19fc _dispatch_worker_thread3
11 libsystem_pthread.dylib        0x182f07fac _pthread_wqthread
12 libsystem_pthread.dylib        0x182f07b08 start_wqthread

Command or Code

navigator.geolocation.watchPosition(
                getPositionSuccess,
                function (err) {...},
                {
                    enableHighAccuracy: true,
                    timeout: 5000,
                    maximumAge: 5000
                }
            )

Environment, Platform, Device

Occurs on iOS on all devices.

Version information

Cordova version: 8.1.2
cordova-plugin-geolocation: 4.0.1
Ionic framework: 1
Ionic cli: 4.12.0

Checklist

  • I searched for already existing GitHub issues about this
  • [-] I updated all Cordova tooling to their most recent version
  • I included all the necessary information above

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.