Help guide the NativeScript roadmap! Participate in the community survey. 📝

NativeScript Angular

Location

nativescript-geolocation plugin provides API for getting and monitoring location for NativeScript app.

Basic Location Example

Import nativescript-geolocation plugin

import { Location, getCurrentLocation, isEnabled, distance, enableLocationRequest } from "nativescript-geolocation";

Enable location services

enableLocationRequest(true);

Check - is location enabled

isEnabled().then(function (isLocationEnabled) {
    let message = "Location services are not available";
    if (isLocationEnabled) {
        message = "Location services are available";
    }
    alert(message);
}, function (e) {
    console.log("Location error received: " + (e.message || e));
});

Get distance between two locations

let startLocation: Location = new Location();
startLocation.longitude = this.startpointLongitude;
startLocation.latitude = this.startpointLatitude;

let endLocation: Location = new Location();
endLocation.longitude = this.endpointLongitude;
endLocation.latitude = this.endpointLatitude;
this.distance = distance(startLocation, endLocation);

Get current location

getCurrentLocation({
    desiredAccuracy: Accuracy.high,
    timeout: 5000
 })
    .then(location => {
        console.log("Location received: " + location);
        this.startpointLatitude = location.latitude;
        this.startpointLongitude = location.longitude;
    }).catch(error => {
        console.log("Location error received: " + error);
        alert("Location error received: " + error);
    });

Improve this document

Demo Source


Location Monitoring Example

Import nativescript-geolocation plugin

import { Location, enableLocationRequest, watchLocation, clearWatch } from "nativescript-geolocation";

Receive continuous location updates

if (this.isMonitoring) {
    clearWatch(this.listener);
    this.isMonitoring = false;
    this.buttonText = "Start location monitoring";
} else {
    this.listener = watchLocation((loc: Location) => {
        if (loc) {
            console.log(loc.longitude + " " + loc.latitude);
            this.monitorLongitude = (loc.longitude).toFixed(4);
            this.monitorLatitude = (loc.latitude).toFixed(4);
            this.monitorAltitude = (loc.altitude).toFixed(2);
            this.monitorDirection = (loc.direction).toFixed(2);
            this.monitorSpeed = (loc.speed).toFixed(2);
        }
    }, (e) => {
        console.log("Error: " + e.message);
    }, this.options);

    this.isMonitoring = true;
    this.buttonText = "Stop location monitoring";
}

Improve this document

Demo Source