Giter Site home page Giter Site logo

nativescript / nativescript-geolocation Goto Github PK

View Code? Open in Web Editor NEW
138.0 138.0 77.0 20.52 MB

Geolocation plugin to use for getting current location, monitor movement, etc

License: Apache License 2.0

TypeScript 79.73% Shell 2.62% CSS 1.41% HTML 2.11% JavaScript 0.45% Vue 8.78% SCSS 4.90%
android geolocation ios mobile nativescript plugin

nativescript-geolocation's Introduction

Source moved and managed here: https://github.com/NativeScript/plugins/tree/main/packages/geolocation

NativeScript Geolocation apple android

npm npm Build Status

Geolocation plugin to use for getting current location, monitor movement, etc.

Installation

In Command prompt / Terminal navigate to your application root folder and run:

tns plugin add nativescript-geolocation

Usage

The best way to explore the usage of the plugin is to inspect the demo app in the plugin's root folder. In demo folder you can find the usage of the plugin for TypeScript non-Angular application. Refer to demo/app/main-page.ts.

In short here are the steps:

Import the plugin

TypeScript

import * as geolocation from "nativescript-geolocation";
import { Accuracy } from "tns-core-modules/ui/enums"; // used to describe at what accuracy the location should be get

Javascript

var geolocation = require("nativescript-geolocation");

Request permissions

geolocation.enableLocationRequest();

Call plugin methods

// Get current location with high accuracy
geolocation.getCurrentLocation({ desiredAccuracy: Accuracy.high, maximumAge: 5000, timeout: 20000 })

API

Properties

Location

Property Default Description
latitude - The latitude of the geolocation, in degrees.
longitude - The longitude of the geolocation, in degrees.
altitude - The altitude (if available), in meters above sea level.
horizontalAccuracy - The horizontal accuracy, in meters.
verticalAccuracy - The vertical accuracy, in meters.
speed - The speed, in meters/second over ground.
timestamp - The time at which this location was determined.

Options

Property Default Description
desiredAccuracy? Accuracy.high This will return the finest location available but use more power than any option. Accuracy.any is considered to be about 100 meter accuracy. Using a coarse accuracy such as this often consumes less power.
updateDistance No filter Update distance filter in meters. Specifies how often to update the location. Read more in Apple document and/or Google documents
updateTime 1 minute Interval between location updates, in milliseconds (ignored on iOS). Read more in Google document.
minimumUpdateTime 5 secs Minimum time interval between location updates, in milliseconds (ignored on iOS). Read more in Google document.
maximumAge - How old locations to receive in ms.
timeout 5 minutes How long to wait for a location in ms.
iosAllowsBackgroundLocationUpdates false If enabled, UIBackgroundModes key in info.plist is required (check the hint below). Allow the application to receive location updates in background (ignored on Android). Read more in Apple document
iosPausesLocationUpdatesAutomatically true Allow deactivation of the automatic pause of location updates (ignored on Android). Read more in Apple document

If iosAllowsBackgroundLocationUpdates is set to true, the following code is required in the info.plist file:

<key>UIBackgroundModes</key>
<array>
   <string>location</string>
</array>

Methods

Method Returns Description
getCurrentLocation(options: Options) Promise Get current location applying the specified options (if any). Since version 5.0 of the plugin, it will use requestLocation API for devices using iOS 9.0+. In situation of poor or no GPS signal, but available Wi-Fi it will take 10 sec to return location.
watchLocation(successCallback: successCallbackType, errorCallback: errorCallbackType, options: Options) number Monitor for location change.
clearWatch(watchId: number) void Stop monitoring for location change. Parameter expected is the watchId returned from watchLocation.
enableLocationRequest(always?: boolean, iosOpenSettingsIfLocationHasBeenDenied?: boolean) Promise<void> Ask for permissions to use location services. The options are applicable only for iOS. When always is true, it opens a custom prompt message and the following keys are required: NSLocationAlwaysAndWhenInUseUsageDescription (iOS 11.0+) OR NSLocationAlwaysUsageDescription (iOS 8.0-10.0) and NSLocationWhenInUseUsageDescription. Read more about request always usage . When iosOpenSettingsIfLocationHasBeenDenied is true, the settings app will open on iOS so the user can change the location services permission.
isEnabled Promise<boolean> Resolves true or false based on the location services availability.
distance(loc1: Location, loc2: Location) number Calculate the distance between two locations. Returns the distance in meters.

Known Issues

Version Conflicts – Google Play Services

If you have installed multiple plugins that use the Google Play Services you might run into version conflicts. For example, you may encounter the error below when using the nativescript-google-maps-sdk plugin:

Cannot enable the location service. Error: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/internal/zzbck;

In order to fix this you might pin the version number in your app/App_Resources/Android/before-plugins.gradle file (if the file does not exist, just create it):

android {  
  // other stuff here

  project.ext {
    googlePlayServicesVersion = "16.+"
  }
}

Contribute

We love PRs! Check out the contributing guidelines. If you want to contribute, but you are not sure where to start - look for issues labeled help wanted.

Get Help

Please, use github issues strictly for reporting bugs or requesting features. For general questions and support, check out Stack Overflow or ask our experts in NativeScript community Slack channel.

nativescript-geolocation's People

Contributors

akang avatar akera-io avatar bradmartin avatar denisraison avatar dimitartachev avatar dimitartodorov avatar dtopuzov avatar elena-p avatar etabakov avatar hdeshev avatar hettiger avatar ignaciolarranaga avatar jgou avatar lini avatar liooo avatar manojdcoder avatar mrvonkey avatar nathanwalker avatar nsplugins avatar rynop avatar sebj54 avatar speigg avatar surdu avatar tbozhikov avatar tgpetrov avatar vladimiramiorkov 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

nativescript-geolocation's Issues

Timeout searching for location on Android (Nativescript 3.0.3)

I saw issues reported on forum and this repository about issues on reading location on Android on NS3.0. I just want to report that it also not working on Nativescript Sample application.

Steps to reproduce:

The plugin runs fine on iOS.

Attached please found the screenshot for your reference.

Versions:
│ Component │ Current version │ Latest version │ Information │
│ nativescript │ 3.0.3 │ 3.0.3 │ Up to date │
│ tns-core-modules │ 3.0.1 │ 3.0.1 │ Up to date │
│ tns-android │ 3.0.1 │ 3.0.1 │ Up to date │
│ tns-ios │ 3.0.1 │ 3.0.1 │ Up to date │

Hope this can help and let me know if need any further information.

Regards
Clarence
ns-android-location-error

Timeout while searching for location - Angular 2

Description Of The Issue

When requesting a users location after a successful location services request, the getCurrentLocation method times out.

import {Component, OnInit} from "@angular/core";
var geolocation = require("nativescript-geolocation");

@Component({
    selector: "my-app",
    templateUrl: "app.component.html",
})
export class AppComponent implements OnInit {
    status:string = "Location services not enabled";

    ngOnInit() {
        if (!geolocation.isEnabled()) {
           geolocation.enableLocationRequest().then(() => {
                this.getLocation();
            });
        }
        else {
            this.getLocation();
        }
    }

    getLocation() {
       // this method times out when called from the enableLocationRequest promise
        geolocation.getCurrentLocation({ timeout: 20000 }).then((location) => {
            this.status = `Latitide: ${location.latitude}, Latitude: ${location.longitude}`;
        });
    }
}

Expected Result

The application should request access to the user's location and then display their latitude and longitude.

Actual Results

The getCurrentLocation method times out.

geolocation-timeout-log.txt

Steps To Recreate

  1. tns create geolocation --ng
  2. replace the code in app.component.ts with the code above
  3. tns livesync ios --emualtor --watch or tns livesync android --watch (Android Studio Emulator)

Environment Configuration

  • NativeScript CLI 2.2.1
  • Node 5.4.0
  • iOS Simulator version 9.3
  • Android API version 22 Emulator

Does it work in background

Hi Guys,
I wanted to know if the nativescript-geolocation provide location update while app in background ?
thanks!

"getCurrentLocation" response is very slow, unless using together with google maps sdk

When I start the app for the first time, everything works fine:

  1. I get my location in 1-3s
geolocation.getCurrentLocation({
	desiredAccuracy: 3, 
	updateDistance: 1, 
	maximumAge: 20000, 
	timeout: 20000
}).then(function(loc) {
	console.log(JSON.stringify(loc, null, 4));
	if (loc) {
		return loc;
	}
}).catch(function(response){
	console.log(response);
});
  1. In about 5-10s I am asking for my location again. It also returns it in 1-3s.

  2. Then I start nativescript-google-maps-sdk plugin. Also I enable setMyLocationEnabled, that enables locate_me button and blue_pin as my device on the map:

gMap.setMyLocationEnabled(true);
  1. At this point I am updating my current location every 10s and it returns it in 1-3s. All is well.

PROBLEM

If the app has been opened at least once before, and it has cached its data now, opening it the second time makes my getCurrentLocation get response very slowly.

  1. I ask my location (repeatedly, until I get it), but it will return Error: Timeout while searching for location! at first try, then it will return it correctly at second try.

  2. In about 5-10s I am asking for my location again. However, it will behave exactly like in point 1.

  3. I start the gmaps plugin, enabling setMyLocationEnabled.

  4. Now every continuous getCurrentLocation returns the location normaly in 1-3s.

Conclusion - there is some sort of problem in getting the location data, probably bad interaction with caching data. And this problem dissappears when nativescript-google-maps-sdk plugin plugins setMyLocationEnabled method is enabled.

Tested on Android.

Http service not getting called

Hi,

I have a service in "enableLocationRequest" callback, I see the service function being called but I dont see the service making a http request. This is happening when I make a fresh install of app on emulator.

But if I force kill the app and open it again, I see it to getting all the data. This is happening in Android, have not tested it on IOS.

I have latest build of TNS.

I have some basic code uploaded here
https://github.com/MadhuSudhanBhaskar/NativeNew
Upfront Not a production code

Inaccurate

I decided to do some real testing rather than emulated, and the results are woefully inaccurate. I walked around the block and found my location would stick for 10+ seconds sometimes, and half the time it showed me as being nowhere near the path I was on

UI: current location using geolocation

Hi,
I am using geolocation plugin in NS-core to get the current location.
Here is the code

var location = geolocation.getCurrentLocation({desiredAccuracy: 3, updateDistance: 10, maximumAge: 20000, timeout: 20000}).
then(function(loc) {
if (loc) {
console.log("Current location is: " + JSON.stringify(loc));
}
}, function(e){
console.log("Error: " + e.message);
});

the code is giving the values of latitude, longitude, altitude, horizontalAccuracy, verticalAccuracy, direction, timestamp, android ..

My question is to which function I have to feed those values to get the current location(string) ??

When will be confirmed?

When this module be confirmed and allowed to be tested in companion app? Or maybe there is a way to test it without building actual app?

Crashing with version 3.0 on Android

The sample app below runs fine on iOS but crashes on Android. If I comment the watchId part, the app runs ok on Android, which confirms the issue is with the geolocation plugin. Can you please check? Thanks!


var observable = require("data/observable");
var pageModule = require("ui/page");
var viewModel = new observable.Observable();
var geolocation = require("nativescript-geolocation");
var view = require("ui/core/view");

var activeLoc = [];
var pilotList
var watchId

var drawer;
exports.pageLoaded = function(args) {
    page = args.object;
    drawer = view.getViewById(page, "sideDrawer");
    pilotList = view.getViewById(page, "pilotList");
    viewModel.set("activeList",activeLoc);
    page.bindingContext = viewModel;
}

exports.toggleDrawer = function() {
    drawer.toggleDrawerState();
};


//Update dashboard
function updateDash(args) {
    var lat = args.latitude;
    var lon = args.longitude;
    activeLoc.push({listLat:lat,listLon:lon})   
}
exports.updateDash = updateDash;

//starts dashboard
watchId = geolocation.watchLocation(
function (loc) {
    if (loc) {
      updateDash(loc)                
    }
}, 
function(e){
    console.log("Error: " + e.message);
},
{desiredAccuracy: 3, updateDistance: 10, maximumAge:5000}); 

The xml file:

<Page xmlns="http://schemas.nativescript.org/tns.xsd"  xmlns:sd="nativescript-telerik-ui/sidedrawer" xmlns:x="nativescript-statusbar" backgroundSpanUnderStatusBar="true" class="page" actionBarHidden="false" loaded="pageLoaded">
    <Page.actionBar>
        <ActionBar title="Dashboard">
            <StackLayout orientation="horizontal"
                ios:horizontalAlignment="center"
                android:horizontalAlignment="left">
                <Image src="res://bf_logo" class="action-image"></Image>
            </StackLayout>
        </ActionBar>
    </Page.actionBar>

<x:StatusBar ios:barStyle="light" android:barStyle="#303030" />


    <sd:RadSideDrawer id="sideDrawer" drawerLocation="left">
        <!-- side drawer content -->
        <sd:RadSideDrawer.drawerContent>
            <StackLayout class="sidedrawer-left">

                <StackLayout class="sidedrawer-content">
                    <ListView id="pilotList" items="{{ activeList }}">
                        <ListView.itemTemplate>
                            <GridLayout columns="*,*2,*">
                                <Label text="{{ listLat }}" col="0"  class="listNick" />
                                
                            </GridLayout>
                        </ListView.itemTemplate>
                    </ListView>
                </StackLayout>
            </StackLayout>
        </sd:RadSideDrawer.drawerContent>
      
      
        <!-- The main content -->
        <sd:RadSideDrawer.mainContent>

                <!-- <GridLayout columns="*" rows="60,*,50,32" style.backgroundColor="#182126">  -->
                <GridLayout columns="*" rows="60,*,60" style.backgroundColor="#36283D">   

                    
                    <ContentView row="2" tap="toggleDrawer">
                        </ContentView>

                </GridLayout>

            </sd:RadSideDrawer.mainContent>
    </sd:RadSideDrawer>
</Page>

TypeError: undefined is not a constructor (evaluating 'new nativescript_geolocation_1.Location()')

My package.json is as follows:
"nativescript": {
"id": "org.nativescript.test",
"tns-ios": {
"version": "2.5.0"
}
},
"dependencies": {
"@angular/common": "2.4.3",
"@angular/compiler": "2.4.3",
"@angular/core": "2.4.3",
"@angular/forms": "2.4.3",
"@angular/http": "2.4.3",
"@angular/platform-browser": "2.4.3",
"@angular/platform-browser-dynamic": "2.4.3",
"@angular/router": "3.4.3",
"nativescript-angular": "1.4.0",
"nativescript-couchbase": "^1.0.17",
"nativescript-geolocation": "0.0.19",
"nativescript-theme-core": "~1.0.2",
"reflect-metadata": "~0.1.8",
"rxjs": "~5.0.1",
"tns-core-modules": "2.5.1"
},
"devDependencies": {
"babel-traverse": "6.23.1",
"babel-types": "6.23.0",
"babylon": "6.16.1",
"lazy": "1.0.11",
"nativescript-dev-android-snapshot": "^0..",
"nativescript-dev-typescript": "~0.3.5",
"typescript": "~2.1.0",
"zone.js": "~0.7.2"
}

I get the following error at runtime when it tries to create a new instance of the Location class on iOS:
TypeError: undefined is not a constructor (evaluating 'new nativescript_geolocation_1.Location()')

enableLocationRequest promise elusive?

i am having this problem on ios 10: can't seem to get my hands on the promise returned by enableLocationRequest. Here's a snippet:

geolocation.enableLocationRequest()
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
});

neither 'then' nor 'catch' branches execute. the next thing i see is the code which calls the above reporting an exception: 'Authorization denied'. what am i doing wrong here?

thanks!

Issue with creating new Location from code behind

When you try to create a new Location from code behind the following error will be throw:

CONSOLE ERROR [native code]: ERROR TypeError: undefined is not a constructor (evaluating 'new nativescript_geolocation_1.Location()')
CONSOLE ERROR [native code]: ERROR CONTEXT [object Object]

The problem could be reproduced in this sample project.
Archive.zip

How to prevent multiple watchLocation listeners ?

Hi,

Is there some option to stop all active watchLocation listeners started from the app ?

In my case I have component which starts watchLocation listener every time when is visited.
The problem is the previous listeners don't stop to listen for gps location ( and i have multiple active listeners for gps location ).

How can i stop them without to know their watch IDs ?

I tried with simple check :

               if ( !this.watchId ) {
                    this.watchId = geolocation.watchLocation(this.locationReceived, this.error, {
                        desiredAccuracy: 20,
                        updateDistance: 0,
                        minimumUpdateTime: 15000,
                        maximumAge: 6000
                    });
                }

But every time this watchID is different for each new visit in the component and accordingly it`s not created ( this doesn't work ) .

Thanks for help !

Mock locations not received

I have Lockito setup to send mock locations on my OnePlus 3T. I see that Google Maps shows the fake locations, so I know that Lockito works correctly, but in my application, the location change handler never triggers.

PS: I took care so that the mock accuracy in bellow desider accuracy.

[Android] Enable Location

Is there a way to enable geolocation, in a way similar to that of Google Maps in Android 7?
I ask this because when checking for location, if the user allowed it, and disabled it later, the user is not prompt the permission.

screenshot_20170410-122442
screenshot_20170410-122525

enableLocationRequest() opens multiple settings dialogs in Android

I am using API version 23.

When calling enableLocationRequest(), if the user denies permissions one or more times before finally accepting, it appears to result in a call to the activityRequestPermissionsEvent handler once for every time the enableLocationRequest() was called, each time it is called. If the location service settings were turned off, this results in the user having to back out of the location services setting screen multiple times before getting back to the app.

Console output:

JS: Request 0:
JS: requestCode: 5000 permissions: [Ljava.lang.String;@5735651 grantResults: [I@a0e9eb6
JS: permission not granted!!!
JS: Unhandled Promise rejection: Location service is not enabled or using it is not granted. ; Zone: ; Task: ; Value: Error: Location service is not enabled or using it is not granted.
JS: Error: Uncaught (in promise): Error: Location service is not enabled or using it is not granted.
JS: Request 1:
JS: requestCode: 5000 permissions: [Ljava.lang.String;@8af5590 grantResults: [I@c197e89
JS: permission not granted!!!
JS: requestCode: 5000 permissions: [Ljava.lang.String;@8af5590 grantResults: [I@c197e89
JS: permission not granted!!!
JS: Unhandled Promise rejection: Location service is not enabled or using it is not granted. ; Zone: ; Task: ; Value: Error: Location service is not enabled or using it is not granted.
JS: Error: Uncaught (in promise): Error: Location service is not enabled or using it is not granted.
JS: Request 2:
JS: requestCode: 5000 permissions: [Ljava.lang.String;@9a7becb grantResults: [I@49046a8
JS: permission not granted!!!
JS: requestCode: 5000 permissions: [Ljava.lang.String;@9a7becb grantResults: [I@49046a8
JS: permission not granted!!!
JS: requestCode: 5000 permissions: [Ljava.lang.String;@9a7becb grantResults: [I@49046a8
JS: permission not granted!!!
JS: Unhandled Promise rejection: Location service is not enabled or using it is not granted. ; Zone: ; Task: ; Value: Error: Location service is not enabled or using it is not granted.
JS: Error: Uncaught (in promise): Error: Location service is not enabled or using it is not granted.
JS: Request 3:
JS: requestCode: 5000 permissions: [Ljava.lang.String;@ad6edf2 grantResults: [I@52f3c43
JS: permission not granted!!!
JS: requestCode: 5000 permissions: [Ljava.lang.String;@ad6edf2 grantResults: [I@52f3c43
JS: permission not granted!!!
JS: requestCode: 5000 permissions: [Ljava.lang.String;@ad6edf2 grantResults: [I@52f3c43
JS: permission not granted!!!
JS: requestCode: 5000 permissions: [Ljava.lang.String;@ad6edf2 grantResults: [I@52f3c43
JS: permission not granted!!!
JS: Unhandled Promise rejection: Location service is not enabled or using it is not granted. ; Zone: ; Task: ; Value: Error: Location service is not enabled or using it is not granted.
JS: Error: Uncaught (in promise): Error: Location service is not enabled or using it is not granted.

As you can see, the fourth request results in the callback being executed 4 times. I was able to solve this issue for myself by modifying the code in the enableLocationRequestCore() method in application.android.js starting at line 129 to the following:

        var requestPermissionsResultHandler_1 = function (data) {
            appModule.android.off(appModule.AndroidApplication.activityRequestPermissionsEvent, requestPermissionsResultHandler_1);
            console.log('requestCode: ' + data.requestCode + ' permissions: ' + data.permissions + ' grantResults: ' + data.grantResults);
            if (data.requestCode === 5000) {
                if (data.grantResults.length > 0 && data.grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                    console.log("permission granted!!!");
                    enableLocationServiceRequest(currentContext, successCallback, successArgs, errorCallback, errorArgs);
                }
                else {
                    console.log("permission not granted!!!");
                    if (errorCallback) {
                        errorCallback.apply(_this, errorArgs);
                    }
                }
            }
        };
        appModule.android.on(appModule.AndroidApplication.activityRequestPermissionsEvent, requestPermissionsResultHandler_1);

This unbinds the activityRequestPermissionsEvent handler when it is called, in the same manner you do in the enableLocationServiceRequest() function in the same file.

iOS 9+ Location Request does nothing

Hi

enableLocationRequest function does nothing when called on iOS 9+.
As i'm a NativeScript beginner, i've spent multiple hours to understand where the problem was.
I've found it and is located in the following js file:
node_modules/nativescript-geolocation/nativescript-geolocation.ios.js
The Os Version test doesn't permit to match iOS 9+.
It can be corrected by something like the following:

 function enableLocationRequest(always) {
-    if (platformModule.device.osVersion.indexOf("8") === 0) {
+    var intOsVersionMajor = parseInt(platformModule.device.osVersion.split('.')[0]);
+    if (intOsVersionMajor >= 8) {

Regards
Stéphane

Subscribing for location changes while app is suspended in background.

Is it possible for a Nativescript app to use geolocation while an app is in the background or suspended. For example, Apple provide a Significant-Change Location Service that from my understanding "wakes" the app up for an event?

https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html

Any examples or guidance out there? I've had trouble finding any :)
Basically, I'm trying to make an app that will prompt the user when they encounter a specific location (even if the app isn't currently open).

“JS: permission not granted!!!” although never asked

Hi,

on Android 6 geolocation.enableLocationRequest() sometimes does not work.
I get a message “JS: permission not granted!!!” in the console, although the prompt for it never came up, but nothing else happens, the error function inside .then() does also not get called (success function neither).

Deleting the app does not change anything, after some hours it then suddenly works again.

edit: had wrong function its about enableLocationRequest not getCurrentLocation

Version 0.0.10 gives build error with tns 2.0

Hi,

I get the error "Processing node_modules failed. TypeError: Invalid Version: 2.0" with version 0.0.10 of the plugin on tns version 2.0.

Downgrading to 0.0.8 of the plugin works fine.

Thanks, Simon

"getCurrentLocation" function is giving error in nativescript 2.5.0(IOS).

Hi,

I am working on a nativescript-Angular2 app. I'm trying to use nativescript-geolocation plugin to fetch the user's location. But when I am calling the "getCurrentLocation()" method, it is giving error, saying "New location is older than requested maximum age!"

Here is my Environment Info:
nativescript 2.5.0
tns-core-modules 2.4.4
tns-android 2.5.0
tns-ios 2.5.0
nativescript-geolocation 0.0.19

Here is my code sample.

ngOnInit() {
   if (!isEnabled()) {
       enableLocationRequest();
     }
  } 

buttonTap() {
     var location = getCurrentLocation({ desiredAccuracy: 3, updateDistance: 10, maximumAge: 20000, timeout: 20000 }).
      then(function (loc) {
        if (loc) {
          console.log("User location is: " + loc);
        }
      }, function (e) {
        console.log("Error: " + e.message);
     });
 }

[Request] Add isEnabledOnDevice

Need a second isEnabled for the redirection to the device settings.

isEnabledOnApp = isEnabled;
isEnabledOnDevice = Is Location enabled on (Android/iOS) Settings.

Thanks you.

how to setMyLocationEnabled(true) after enableLocationRequest() success?

I'm trying to setmylocationenable to true when loading the page and the user gives permission, but I get

I have something like this:

`public onMapReady(event): void {

    this.mapView = event.object;
    
    if(!GeoLocationService.isEnabled()){
         GeoLocationService.enableLocationRequest().then(function(res){
             this.enableLocationLayer();
         }, function(error){
             
         }); 
    }else{
        this.enableLocationLayer();
    }

}

public enableLocationLayer(): void{

      if(this.mapView.android) {
            this.mapView.gMap.setMyLocationEnabled(true);
        }
        else if (this.mapView.ios) {
            this.mapView.gMap.myLocationEnabled(true);
        }

}

`
But I get

JS: permission granted!!!
JS: EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'enableLocationLayer' of null
JS: ORIGINAL STACKTRACE:
JS: Error: Uncaught (in promise): TypeError: Cannot read property 'enableLocationLayer' of null at resolvePromise (file:///data/data/org.nativescript.testapp/files/app/tns_modules/nativescript-angular/zone.js/dist/zone-nativescript.js:416:31)...

It actually works but I have to go and come back to the page to see the locate icon on the top right hand of the map.

Thanks for your help.

watchLocation does not work on my end

Hi,

watchLocation appears not to be working on my end on iOS, both in the simulator and test device (iPhone).

Code:

    geolocation.watchLocation(
      updatePosition,
      function ( e ) {
         alert( 'Error updating position: ' + e.message )
      },
      {
         desiredAccuracy : 10,
         updateTime : 2500
      }
    );

function updatePosition( loc ) {
   console.log( 'Location updated', loc );
}

The updatePosition is never called.

From time to time I get the error callback called, but not always.

Let me know what further details to provide.

Location imprecision

Hi there,

I'm dropping this here : It's really tough to manage GPS options with nativescript-geolocation, for multiple reasons :

First of all, my composer :

 "@angular/common": "2.1.2",
    "@angular/compiler": "2.1.2",
    "@angular/core": "2.1.2",
    "@angular/forms": "2.1.2",
    "@angular/http": "2.1.2",
    "@angular/platform-browser": "2.1.2",
    "@angular/platform-browser-dynamic": "2.1.2",
    "@angular/router": "3.1.2",
    "nativescript-angular": "1.1.3",
    "nativescript-theme-core": "^0.2.1",
    "reflect-metadata": "~0.1.8",
    "rxjs": "5.0.0-beta.12",
    "tns-core-modules": "2.4.0",
    "nativescript-audio": "^2.0.6",
    "nativescript-background-http": "^2.3.0",
    "nativescript-geolocation": "0.0.13",
    "nativescript-google-maps-sdk": "git+https://github.com/hubupfr/nativescript-google-maps-sdk.git",
    "nativescript-google-maps-utils": "git+https://github.com/hubupfr/nativescript-google-maps-utils.git",
    "nativescript-permissions": "^1.2.0",
    "nativescript-phone": "^1.2.0",
    "nativescript-ripple": "^1.0.1",
    "nativescript-snackbar": "^1.1.4",
    "nativescript-swiss-army-knife": "1.0.7",
    "nativescript-telerik-ui": "^1.4.1",
    "nativescript-pdf-view": "^1.2.0",
    "moment": "^2.15.1"

And I'm running it on android

  1. It's not easy to understand how to manage the geolocation.watchLocation() options, and default options - that seems to work - are not suited for precise tracking (I understand that they were written for a scarce location, and it can not cover all case).
    Maybe would it be a nice idea to add several JSON Options in the docs for different use cases ? (very scarce / scarce / fine with battery concerns / very fine...)

  2. Now that's an issue I guess, let's look at this snippet :

public followLocation(toggle:boolean) {
        if(toggle && !this.watchId) {
            // One service of mine that requests location permission
            this._toolsService.requireGPSPermission().then(() => {
                this.watchId = geolocation.watchLocation(
                    (location) => {
                        //My handling
                        this.updateCameraFromPoint(new Point(location.latitude, location.longitude));
                    },
                    function(e){
                        console.log("Error: " + e.message);
                    },
                    { minimumUpdateTime: 500, updateDistance : 2, maximumAge : 5000 })

            });

        } else if (!toggle && this.watchId) {
            geolocation.clearWatch(this.watchId);
        }
    }

Looks like promissing. Well no. The fine location of the phone is not even triggered and position update appears every ... lots of seconds.
Now, let's do a little workaround.

public followLocation(toggle:boolean) {
       if(toggle && !this.watchId) {
           this._toolsService.requireGPSPermission().then(() => {
               this.mapView.gMap.setMyLocationEnabled(true);
               this.mapView.gMap.getUiSettings().setMyLocationButtonEnabled(false);
               console.log("start watchid");
               this.watchId = geolocation.watchLocation(
                   (location) => {
                       this.updateCameraFromPoint(new Point(location.latitude, location.longitude));
                   },
                   function(e){
                       console.log("Error: " + e.message);
                   },
                   { minimumUpdateTime: 500, updateDistance : 2, maximumAge : 5000 })

           });

       } else if (!toggle && this.watchId) {
           this.mapView.gMap.setMyLocationEnabled(false);
           geolocation.clearWatch(this.watchId);
           console.log("stopping watchid");
       }
   }

Looks like nothing changed and I only have launched a location tracking from the very good google maps SDK. Surprisingly, now it works perfectly.

My guess is that the options are not working well, and calling this.mapView.gMap.setMyLocationEnabled(true); triggers a new set of options for the Location module.

So am I clearly missunderstanding the nativescript-location, or is there some kind of bugs in there ?

Getting desperate with Geolocation 3.0.0

My app (a GPS dashboard) was running fine on both Android (device) and iOS Simulator until I had the "great" idea of updating everything to 3.0.x. The moment I did it, nothing else is working anymore due issues with the geolocation plugin.

Fact is, it is not updating the coordinates on Android (or even worse, crashing). See the sample below:
page.xml

<Page xmlns="http://schemas.nativescript.org/tns.xsd" class="page" loaded="pageLoaded">
    <StackLayout class="p-20">
    <Label text="Coordinates" class="h2 text-center" textWrap="true"/>
        <Label text="{{ message }}" class="h2 text-center" textWrap="true" id="messageText"/>
    </StackLayout>
</Page>

page.js

var observable = require("data/observable");
var pageModule = require("ui/page");
var viewModel = new observable.Observable();
var geolocation = require("nativescript-geolocation");


var messageText
var loca
exports.pageLoaded = function(args) {
    page = args.object;
    messageText = page.getViewById("messageText");

    page.bindingContext = { message:loca};
}



if (!geolocation.isEnabled()) {
        geolocation.enableLocationRequest();
}


watchId = geolocation.watchLocation(
    function (loc) {
        if (loc) {
            console.log("Received location: " + loc);
            loca = loc
            messageText.text = loca.latitude+", "+loca.longitude
        }
    }, 
    function(e){
        console.log("Error: " + e.message);
    }, 
    {desiredAccuracy: 3, updateDistance: 10, minimumUpdateTime : 1000 * 1});

It is working fine on the iOS Simulator and crashing on Android:

An uncaught Exception occurred on "main" thread.
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.nativescript.geoLocationTest/com.tns.NativeScriptActivity}: com.tns.NativeScriptException: 
Calling js method onCreate failed

Error calling module function 

Error: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
    android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:453)
    com.tns.Runtime.callJSMethodNative(Native Method)
    com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1021)
    com.tns.Runtime.callJSMethodImpl(Runtime.java:903)
    com.tns.Runtime.callJSMethod(Runtime.java:890)
    com.tns.Runtime.callJSMethod(Runtime.java:874)
    com.tns.Runtime.callJSMethod(Runtime.java:866)
    com.tns.NativeScriptActivity.onCreate(NativeScriptActivity.java:13)
    android.app.Activity.performCreate(Activity.java:6237)
    android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    android.app.ActivityThread.-wrap11(ActivityThread.java)
    android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    android.os.Handler.dispatchMessage(Handler.java:102)
    android.os.Looper.loop(Looper.java:148)
    android.app.ActivityThread.main(ActivityThread.java:5417)
    java.lang.reflect.Method.invoke(Native Method)
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
File: "file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js, line: 149, column: 13

StackTrace: 
	Frame: function:'enableLocationRequestCore', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js', line: 149, column: 14
	Frame: function:'watchLocation', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js', line: 168, column: 9
	Frame: function:'', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/main-page.js', line: 23, column: 23
	Frame: function:'require', file:'', line: 1, column: 266
	Frame: function:'global.loadModule', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/globals/globals.js', line: 30, column: 31
	Frame: function:'resolvePageFromEntry', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame-common.js', line: 95, column: 40
	Frame: function:'FrameBase.navigate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame-common.js', line: 177, column: 20
	Frame: function:'ActivityCallbacksImplementation.onCreate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame.js', line: 678, column: 19
	Frame: function:'NativeScriptActivity.onCreate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/activity.js', line: 16, column: 25


Error: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
    android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:453)
    com.tns.Runtime.callJSMethodNative(Native Method)
    com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1021)
    com.tns.Runtime.callJSMethodImpl(Runtime.java:903)
    com.tns.Runtime.callJSMethod(Runtime.java:890)
    com.tns.Runtime.callJSMethod(Runtime.java:874)
    com.tns.Runtime.callJSMethod(Runtime.java:866)
    com.tns.NativeScriptActivity.onCreate(NativeScriptActivity.java:13)
    android.app.Activity.performCreate(Activity.java:6237)
    android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    android.app.ActivityThread.-wrap11(ActivityThread.java)
    android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    android.os.Handler.dispatchMessage(Handler.java:102)
    android.os.Looper.loop(Looper.java:148)
    android.app.ActivityThread.main(ActivityThread.java:5417)
    java.lang.reflect.Method.invoke(Native Method)
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
File: "<unknown>, line: 1, column: 265

StackTrace: 
	Frame: function:'enableLocationRequestCore', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js', line: 149, column: 14
	Frame: function:'watchLocation', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js', line: 168, column: 9
	Frame: function:'', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/main-page.js', line: 23, column: 23
	Frame: function:'require', file:'', line: 1, column: 266
	Frame: function:'global.loadModule', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/globals/globals.js', line: 30, column: 31
	Frame: function:'resolvePageFromEntry', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame-common.js', line: 95, column: 40
	Frame: function:'FrameBase.navigate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame-common.js', line: 177, column: 20
	Frame: function:'ActivityCallbacksImplementation.onCreate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame.js', line: 678, column: 19
	Frame: function:'NativeScriptActivity.onCreate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/activity.js', line: 16, column: 25


	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
	at android.app.ActivityThread.-wrap11(ActivityThread.java)
	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
	at android.os.Handler.dispatchMessage(Handler.java:102)
	at android.os.Looper.loop(Looper.java:148)
	at android.app.ActivityThread.main(ActivityThread.java:5417)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: com.tns.NativeScriptException: 
Calling js method onCreate failed

Error calling module function 

Error: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
    android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:453)
    com.tns.Runtime.callJSMethodNative(Native Method)
    com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1021)
    com.tns.Runtime.callJSMethodImpl(Runtime.java:903)
    com.tns.Runtime.callJSMethod(Runtime.java:890)
    com.tns.Runtime.callJSMethod(Runtime.java:874)
    com.tns.Runtime.callJSMethod(Runtime.java:866)
    com.tns.NativeScriptActivity.onCreate(NativeScriptActivity.java:13)
    android.app.Activity.performCreate(Activity.java:6237)
    android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    android.app.ActivityThread.-wrap11(ActivityThread.java)
    android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    android.os.Handler.dispatchMessage(Handler.java:102)
    android.os.Looper.loop(Looper.java:148)
    android.app.ActivityThread.main(ActivityThread.java:5417)
    java.lang.reflect.Method.invoke(Native Method)
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
File: "file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js, line: 149, column: 13

StackTrace: 
	Frame: function:'enableLocationRequestCore', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js', line: 149, column: 14
	Frame: function:'watchLocation', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js', line: 168, column: 9
	Frame: function:'', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/main-page.js', line: 23, column: 23
	Frame: function:'require', file:'', line: 1, column: 266
	Frame: function:'global.loadModule', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/globals/globals.js', line: 30, column: 31
	Frame: function:'resolvePageFromEntry', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame-common.js', line: 95, column: 40
	Frame: function:'FrameBase.navigate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame-common.js', line: 177, column: 20
	Frame: function:'ActivityCallbacksImplementation.onCreate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame.js', line: 678, column: 19
	Frame: function:'NativeScriptActivity.onCreate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/activity.js', line: 16, column: 25


Error: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
    android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:453)
    com.tns.Runtime.callJSMethodNative(Native Method)
    com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1021)
    com.tns.Runtime.callJSMethodImpl(Runtime.java:903)
    com.tns.Runtime.callJSMethod(Runtime.java:890)
    com.tns.Runtime.callJSMethod(Runtime.java:874)
    com.tns.Runtime.callJSMethod(Runtime.java:866)
    com.tns.NativeScriptActivity.onCreate(NativeScriptActivity.java:13)
    android.app.Activity.performCreate(Activity.java:6237)
    android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    android.app.ActivityThread.-wrap11(ActivityThread.java)
    android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    android.os.Handler.dispatchMessage(Handler.java:102)
    android.os.Looper.loop(Looper.java:148)
    android.app.ActivityThread.main(ActivityThread.java:5417)
    java.lang.reflect.Method.invoke(Native Method)
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
File: "<unknown>, line: 1, column: 265

StackTrace: 
	Frame: function:'enableLocationRequestCore', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js', line: 149, column: 14
	Frame: function:'watchLocation', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/nativescript-geolocation/nativescript-geolocation.js', line: 168, column: 9
	Frame: function:'', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/main-page.js', line: 23, column: 23
	Frame: function:'require', file:'', line: 1, column: 266
	Frame: function:'global.loadModule', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/globals/globals.js', line: 30, column: 31
	Frame: function:'resolvePageFromEntry', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame-common.js', line: 95, column: 40
	Frame: function:'FrameBase.navigate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame-common.js', line: 177, column: 20
	Frame: function:'ActivityCallbacksImplementation.onCreate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/frame.js', line: 678, column: 19
	Frame: function:'NativeScriptActivity.onCreate', file:'file:///data/data/org.nativescript.geoLocationTest/files/app/tns_modules/tns-core-modules/ui/frame/activity.js', line: 16, column: 25


	at com.tns.Runtime.callJSMethodNative(Native Method)
	at com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1021)
	at com.tns.Runtime.callJSMethodImpl(Runtime.java:903)
	at com.tns.Runtime.callJSMethod(Runtime.java:890)
	at com.tns.Runtime.callJSMethod(Runtime.java:874)
	at com.tns.Runtime.callJSMethod(Runtime.java:866)
	at com.tns.NativeScriptActivity.onCreate(NativeScriptActivity.java:13)
	at android.app.Activity.performCreate(Activity.java:6237)
	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
	... 9 more
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
	at android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:453)
	... 19 more

getCurrentLocation gets timeout on Android API17

My app works fine on Android API 22 and higher. Got my hands on phone with API 17. Made a fresh tns create test --ng project, with "nativescript-geolocation": "^0.0.17" version. Every request that gets sent, gets timed out.

    ngAfterViewInit() {
        console.log("View initialized...");
        geolocation.getCurrentLocation({
            desiredAccuracy: 3, 
            updateDistance: 1, 
            maximumAge: 20000, 
            timeout: 20000
        }).then(function(loc) {
            console.log("LOC:");
            console.log(JSON.stringify(loc, null, 4));
        }).catch(function(response){
            console.log("E: ", response);
        });
   }

{N} geolocation simple app.

Sorry for open this issue, but I miss an example app. I created an example but not found, at least in the Android 6+ how to give permissions in app

Not working on version 2.5

I keep getting this info while installing:
npm WARN [email protected] requires a peer of tns-core-modules@^3.0.0 || ^3.0.0-rc.1 || >=3.0.0-2017 but none was installed.

How to install it with 2.5?

How to get constant updates on geolocation?

First of all, sorry if this is not the proper forum for my question.

I'm new to Nativescript (used to be a Corona/Lua developer) and I need to create a function (similar to a RuntimeEventListener in Lua) that constantly gets user location and updates a dashboard with speed and altitude, for example.

My current code gets this info only when a button is pressed (which does not make sense for the kind of app I am trying to build). Question is, how to create and invoke such listener/function?

I am coding in Javascript and below it is my current code:

var Observable = require("data/observable").Observable;
var frames = require("ui/frame");

var orientation = require('nativescript-orientation');
  orientation.enableRotation(); // The screen will  rotate 
  console.log(orientation.getOrientation());  // Returns the enum DeviceOrientation value

var dialogs = require("ui/dialogs");  

// Get geo coordinates
var geolocation = require("nativescript-geolocation");
if (!geolocation.isEnabled()) {
        geolocation.enableLocationRequest();
}
/*
var watchID
watchId = geolocation.watchLocation(
    function (loc) {
        if (loc) {
            console.log("(watchid) Received location: " + loc);
        }
    }, 
    function(e){
        console.log("(watchid) Error: " + e.message);
    }, 
    {desiredAccuracy: 3, updateDistance: 10, minimumUpdateTime : 1000 * 20}); // should update every 20 sec according to google documentation this is not so sure.
*/


    //variables for the dashboard and the Origin 
    var originLoc //holds the lat,long of the starting point
    var originHeading = "NNW"
    var originTime = "0"
    var originDistance = "0"

    var mySpeed = "0"
    var myDuration = "00:00"
    var myDistance = "0"
    var myAltitude = "0";
    var myDirection;

    var butAction = "START" //button action when it starts

var fbMeasurement = "imperial";

//Sets the right heading of the compass (if landscape, subtracts 90 degrees)
function headingCompass(args) {
    var compassHead = "";

    if (args>12 && args<=34) {
        compassHead = "NNE";
    } else if (args>34 && args<=57) {
        compassHead = "NE";
    } else if (args>57 && args<=80) {
        compassHead = "ENE";
    } else if (args>80 && args<=102) {
        compassHead = "E";
    } else if (args>102 && args<=124) {
        compassHead = "ESE";
    } else if (args>124 && args<=147) {
        compassHead = "SE";
    } else if (args>147 && args<=170) {
        compassHead = "SSE";
    } else if (args>170 && args<=192) {
        compassHead = "S";
    } else if (args>192 && args<=215) {
        compassHead = "SSW";
    } else if (args>215 && args<=237) {
        compassHead = "SW";
    } else if (args>237 && args<=260) {
        compassHead = "WSW";
    } else if (args>260 && args<=282) {
        compassHead = "W";
    } else if (args>282 && args<=305) {
        compassHead = "WNW";
    } else if (args>305 && args<=327) {
        compassHead = "NW";
    } else if (args>327 && args<=350) {
        compassHead = "NNW";
    } else {
        compassHead = "N";
    }  
    return compassHead;
}



//Gets current location when app starts
var geolocation = require("nativescript-geolocation");
if (!geolocation.isEnabled()) {
        geolocation.enableLocationRequest();
}
var location = geolocation.getCurrentLocation({desiredAccuracy: 3, updateDistance: 10, maximumAge: 20000, timeout: 20000}).
then(function(loc) {
    if (loc) {
        console.log("Current location is: " + loc);
        originLoc = loc;
        if (fbMeasurement === "imperial") {
            myAltitude = parseInt(loc.altitude * 3.28084);
            mySpeed = (loc.speed * 2.23694).toFixed(1);
        } else {
            mySpeed = loc.speed.toFixed(1);
            myAltitude = parseInt(loc.altitude);
        }
        myDirection = headingCompass(loc.direction)
    }
}, function(e){
    console.log("Error: " + e.message);
});


function createViewModel() {
    var viewModel = new Observable();

    viewModel.originHeading = originHeading;
    viewModel.originTime = originTime;
    viewModel.originDistance = originDistance;

    viewModel.mySpeed = mySpeed;
    viewModel.myDuration = myDuration;
    viewModel.myDistance = myDistance;
    viewModel.myAltitude = myAltitude;

    viewModel.butAction = butAction;


    //STARTs
    var watchid;
    viewModel.onTapStart = function(args) {
        if (butAction==="START") {

            //change button color to RED
            var btn = args.object;
            btn.backgroundColor = "#FF0000";
            //change button text to "STOP"
            this.set("butAction","STOP");
            butAction = "STOP";

            watchId = geolocation.watchLocation(
            function (loc) {
                if (loc) {
                    console.log("Received location: " + loc);

                    if (fbMeasurement === "imperial") {
                        myAltitude = parseInt(loc.altitude * 3.28084);
                        mySpeed = (loc.speed * 2.23694).toFixed(1);
                    } else {
                        mySpeed = loc.speed.toFixed(1);
                        myAltitude = parseInt(loc.altitude);
                    }
                    myDirection = headingCompass(loc.direction);


                }
            }, 
            function(e){
                console.log("Error: " + e.message);
            }, 
            {desiredAccuracy: 3, updateDistance: 10, minimumUpdateTime : 1000 * 1}); // should update every 20 sec according to google documentation this is not so sure.

        } else {
            //change button color to GREEN
            var btn = args.object;
            btn.backgroundColor = "#00FF00";
            //change button text to "START"
            this.set("butAction","START")
            butAction = "START";

            if (watchId) {
                geolocation.clearWatch(watchId);
            }
        }


        this.set("myAltitude",myAltitude);
        this.set("mySpeed",mySpeed);
        this.set("myDistance",myDirection);



    }

    return viewModel;
}

exports.createViewModel = createViewModel;

Webpack do not work for "this.constructor = d;"

From @ignaciolarranaga on September 4, 2016 21:9

For example it does not work for the geolocation module, because of this code (extracted from the bundled code):

!*** ../~/nativescript-geolocation/nativescript-geolocation.ios.js ***!
  \*********************************************************************/
/***/ function(module, exports, __webpack_require__) {

    "use strict";
    var __extends = (this && this.__extends) || function (d, b) {
        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };

At runtime it throws:

Sep  4 18:04:19 MacBook-Pro-de-Ignacio xxxx[51653]: 1   0x108ff4c67 -[TNSRuntime executeModule:]
Sep  4 18:04:19 MacBook-Pro-de-Ignacio xxxx[51653]: 2   0x106194322 main
Sep  4 18:04:19 MacBook-Pro-de-Ignacio xxxx[51653]: 3   0x10bb6e92d start
Sep  4 18:04:19 MacBook-Pro-de-Ignacio xxxx[51653]: 4   0x1
Sep  4 18:04:19 MacBook-Pro-de-Ignacio xxxx[51653]: file:///app/bundle.js:145226:26: JS ERROR TypeError: Attempted to assign to readonly property.
Sep  4 18:04:19 MacBook-Pro-de-Ignacio com.apple.CoreSimulator.SimDevice.00A4117D-42D7-4D34-A741-4D4FAA4286CD.launchd_sim[96565] (UIKitApplication:com.gynto.client[0x5ed0][51653]): Service exited due to signal: Segmentation fault: 11

This is just an example, but also happen to me on other modules. The only pattern I was able to found is that happends at: function __() { this.constructor = d; }

Copied from original issue: NativeScript/nativescript-dev-webpack#16

'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: NSFont)'

Since the update to nativescript 3.0, the app crash everytime I request location (getCurrentLocation)

Does anyone already faced this issue?

*** JavaScript call stack:
	(
		0   UIApplicationMain@[native code]
		1   start@file:///app/tns_modules/tns-core-modules/application/application.js:211:26
		2   bootstrapApp@file:///app/tns_modules/nativescript-angular/platform-common.js:72:28
		3   bootstrapModule@file:///app/tns_modules/nativescript-angular/platform-common.js:60:26
		4   anonymous@file:///app/main.js:18:57
		5   evaluate@[native code]
		6   moduleEvaluation@:1:11
		7   @:7:50
		8   promiseReactionJob@:1:11
	)
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: NSFont)'
	*** First throw call stack:
	(
		0   CoreFoundation                      0x0000000108a9ab0b __exceptionPreprocess + 171
		1   libobjc.A.dylib                     0x0000000107e5c141 objc_exception_throw + 48
		2   CoreFoundation                      0x00000001089b56e2 -[__NSDictionaryM setObject:forKey:] + 1042
		3   CoreFoundation                      0x0000000108a1b320 -[NSMutableDictionary addEntriesFromDictionary:] + 320
		4   Foundation                          0x000000010532c7f6 -[NSMutableAttributedString addAttributes:range:] + 295
		5   Foundation                          0x0000000105333607 -[NSAttributedString enumerateAttributesInRange:options:usingBlock:] + 344
		6   UIKit                               0x0000000105abca25 -[NSAttributedString(UILabelAdditions) _ui_synthesizeAttributedSubstringFromRange:usingDefaultAttributes:] + 234
		7   UIKit                               0x0000000105abdcf2 -[UILabel _synthesizedAttributedText] + 836
		8   UIKit                               0x0000000105ac027a -[UILabel _textRectForBounds:limitedToNumberOfLines:includingShadow:] + 743
		9   UIKit                               0x0000000105c2a240 -[UIButton _titleRectForContentRect:calculatePositionForEmptyTitle:] + 1480
		10  UIKit                               0x0000000105c2a2e9 -[UIButton titleRectForContentRect:] + 61
		11  UIKit                               0x0000000105c2e042 -[UIButton _layoutTitleView] + 198
		12  UIKit                               0x0000000105c2e1ef -[UIButton layoutSubviews] + 250
		13  UIKit                               0x00000001058ff20b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1268
		14  QuartzCore                          0x0000000108fbe904 -[CALayer layoutSublayers] + 146
		15  QuartzCore                          0x0000000108fb2526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
		16  UIKit                               0x00000001058ecfe4 -[UIView(Hierarchy) layoutBelowIfNeeded] + 1108
		17  UIKit                               0x0000000105c28b32 __32-[UIButton _beginTitleAnimation]_block_invoke.908 + 125
		18  UIKit                               0x00000001058f4cd4 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 527
		19  UIKit                               0x00000001058c7f07 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 222
		20  UIKit                               0x00000001058c8446 -[UIViewAnimationState animationDidStop:finished:] + 136
		21  QuartzCore                          0x0000000108fb968e _ZN2CA5Layer23run_animation_callbacksEPv + 306
		22  libdispatch.dylib                   0x00000001092c3792 _dispatch_client_callout + 8
		23  libdispatch.dylib                   0x00000001092ab247 _dispatch_main_queue_callback_4CF + 1041
		24  CoreFoundation                      0x0000000108a5f909 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
		25  CoreFoundation                      0x0000000108a25ae4 __CFRunLoopRun + 2164
		26  CoreFoundation                      0x0000000108a25016 CFRunLoopRunSpecific + 406
		27  GraphicsServices                    0x000000010b331a24 GSEventRunModal + 62
		28  UIKit                               0x000000010583c0d4 UIApplicationMain + 159
		29  NativeScript                        0x0000000104cbf8ed ffi_call_unix64 + 85
		30  ???                                 0x0000000126eb79c0 0x0 + 4947933632
	)

enableLocationRequest does not return on enabling or denying

It does resolve if location is already enabled.

But it does neither reject if location permission is denied or resolve if permission was granted and location was enabled.

Or am I doing something wrong?

geolocation.enableLocationRequest()
  .then(resolved => {
    console.log('resolved')
  })
  .catch(rejected =>{
    console.log('rejected')
  })

Heading (direction) between 2 locations

I am trying to reproduce an app from my Suunto watch. Basically, it returns the heading between 2 locations. For example, "N" means that I am currently "north" of the original (first) location.

Suunto has a heading function (see below) that returns this info. Is it possible to have something similar with the geolocation plugin?

HEADING(LAT1, LON1, LAT2, LON2)
Returns the heading from current location to given location.
Script: retVal = Suunto.heading(lat, lon, lat2, lon2)
• lat1: type float, degrees, range [-90,90]
• lon1: type float, degrees, range [-180,180]
• lat2: type float, degrees, range [-90,90]
• lon2: type float, degrees, range [-180,180]
• retVal: type float, degrees, range [0,360]

iOS demo app improvements

Using the app on iOS simulator I noticed the following:

  • If I try to get the current location it doesn't prompt to enable Location service.
  • After pressing 'Start monitoring' button it only shows a few location points and stops.

On a real device, the same as above issues happen plus app does not prompt to enable wi-fi which seems vital.

Component variables not updated while watching location.

Hello, new issue, but might not be related to nativescript geolocation but maybe angular data-binding.


public wid:number;
public distance:number = 0;
public lastLocation:any;

watchLocation() {
        if(!this.wid) {
            this.wid = geolocation.watchLocation((location) => {
                    this.updateDistance(location);
                },
                function(e){
                    console.log("Error: " + e.message);
                },
                { desiredAccuracy: Accuracy.high, updateDistance: 1, minimumUpdateTime: 1000 })

        }
    }
}

updateDistance(location) {
   this.distance = this.distance + geolocation.distance(this.lastLocation, location);
   this.lastLocation = location;
  console.log(distance);
}

This is a sample code of a TS file that watches location. On the other hand, I have my view with :

<Label [texŧ]="distance"></Label>

ISSUE is there : distance label is not updated until I cut the watcher. Anything about it ? 👍

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.