Skip to content

Latest commit

 

History

History
257 lines (218 loc) · 9.74 KB

location.md

File metadata and controls

257 lines (218 loc) · 9.74 KB
title description position slug previous_url
Location
How to work with geographical location data in NativeScript.
10
location
/location

Location

IMPORTANT: Starting with NativeScript 1.5.0, the built-in Location module is deprecated. To implement geolocation in your apps, use the nativescript-geolocation plugin, available via npm. This plugin provides an API similar to the W3C Geolocation API.

The most important difference between the deprecated module and the new plugin is that location monitoring via the plugin returns an id that you can use to stop location monitoring. The nativescript-geolocation plugin also uses an accuracy criteria approach to deliver geolocation. This means that getting a location is powered by the most accurate location provider that is available. For example, if a GPS signal is available and the GPS provider is enabled, the plugin uses GPS; if GPS is not connected, the device falls back to other available providers such as Wi-Fi networks or cell towers).

This approach does not limit location monitoring only to a specific location provider; it can still work with all of them.

You might want to start with this example, which demonstrates how to use the nativescript-geolocation plugin.

To make the plugin available in your app, run the following command:

tns plugin add nativescript-geolocation

To import the module in your code, use: {% nativescript %}

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

{% endnativescript %}

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

Getting information about a location service

NativeScript has a universal way to check if location services are turned on—the isEnabled method. The method returns a Boolean value (true if the location service is enabled).

NOTE: For Android, isEnabled checks if the location service is enabled (any accuracy level). For iOS, the method checks if the location service is enabled for the application in foreground or background mode.

Requesting permissions to use location services

By default, the nativescript-geolocation plugin adds the required permissions in AndroidManiest.xml for Android and Info.plist for iOS. For iOS, the plugin adds two dummy string values which serve as the message when the platform asks for permission to use location services. You can edit this message later.

After you install the plugin, you can request to use location services in the app with the code in Example 1:

Example 1: How to enable location service on a device {% nativescript %}

<Page> 
    <StackLayout>
        <Button text="enable Location" tap="enableLocationTap"/>
    </StackLayout>
</Page>
function enableLocationTap(args) {
    if (!geolocation.isEnabled()) {
        geolocation.enableLocationRequest();
    }
}
exports.enableLocationTap = enableLocationTap;

{% endnativescript %} {% angular %}

<StackLayout>
    <Button text="enable Location" (tap)="enableLocationTap()"></Button>
</StackLayout>

{% endangular %}

{% nativescript %}export function {% endnativescript %}public {% angular %}{% endangular %}enableLocationTap() { 
    if (!isEnabled()) {
        enableLocationRequest();
    }
}

Getting location

You can get location with getCurrentLocation or with watchLocation. Using distance, you can obtain the distance between two locations.

getCurrentLocation

This method gets a single location. It accepts the location options parameter.

getCurrentLocation returns a Promise<Location> where Location and location options are defined as follows.

Class: location

A data class that encapsulates common properties for a geolocation.

Instance properties
Property Type Description
latitude Number The latitude of the geolocation, in degrees.
longitude Number The longitude of the geolocation, in degrees.
altitude Number The altitude (if available), in meters above sea level.
horizontalAccuracy Number The horizontal accuracy, in meters.
verticalAccuracy Number The vertical accuracy, in meters.
speed Number The speed, in meters/second over ground.
direction Number The direction (course), in degrees.
timestamp Object The time at which this location was determined.
android Object The Android-specific location object.
ios CLLocation The iOS-specific CLLocation object.

Interface: options

Provides options for location monitoring.

Properties
Property Type Description
desiredAccuracy Number (Optional) Specifies desired accuracy in meters. NativeScript has a special enum Accuracy that helps to make code more readable. Defaults to Accuracy.any. Such accuracy could be achieved with only wifi and assist GPS from network provider, therefore does not put additional pressure on battery consumption. In order to use high accuracy (requires GPS sensor) set this option to Accuracy.high.
updateDistance Number (Optional) Updates distance filter in meters. Specifies how often to update. Default on iOS is no filter, on Android it is 0 meters.
minimumUpdateTime Number (Optional) Specifies the minimum time interval between location updates, in milliseconds. Ignored on iOS.
maximumAge Number (Optional) Filters locations by how long ago they were received, in milliseconds. For example, if the maximumAge is 5000, you will get locations only from the last 5 seconds.
timeout Number (Optional) Specifies how long to wait for a location, in milliseconds.

Example 2: How to get current location {% nativescript %}

<Page>
    <StackLayout>
        <Button text="Get Current Location" tap="buttonGetLocationTap"/>
    </StackLayout>
</Page>
function buttonGetLocationTap(args) {
	var location = geolocation.getCurrentLocation({desiredAccuracy: 3, updateDistance: 10, maximumAge: 20000, timeout: 20000}).
	then(function(loc) {
		if (loc) {
			console.log("Current location is: " + loc);
		}
	}, function(e){
		console.log("Error: " + e.message);
	});
}
exports.buttonGetLocationTap = buttonGetLocationTap;

{% endnativescript %} {% angular %}

<StackLayout>
    <Button text="Get Current Location" (tap)="buttonGetLocationTap()"></Button>
</StackLayout>

{% endangular %}

{% nativescript %}export function {% endnativescript %}public {% angular %}{% endangular %}buttonGetLocationTap() {
	var location = getCurrentLocation({desiredAccuracy: 3, updateDistance: 10, maximumAge: 20000, timeout: 20000}).
	then(function(loc) {
		if (loc) {
			console.log("Current location is: " + loc);
		}
	}, function(e){
		console.log("Error: " + e.message);
	});
}

watchLocation

With this method, location watching does not stop automatically until the clearWatch method is called. You might need to use this method in apps which require a GPS log or active location tracking.

Example 3: How to handle location chnage event

{% nativescript %}

<Page>
    <StackLayout>
		<Button row="2" text="start monitoring" tap="buttonStartTap"/>
		<Button row="3" text="stop monitoring" tap="buttonStopTap"/>
    </StackLayout>
</Page>
function buttonStartTap() {
	watchId = geolocation.watchLocation(
	function (loc) {
		if (loc) {
			console.log("Received location: " + loc);
		}
	}, 
	function(e){
		console.log("Error: " + e.message);
	}, 
	{desiredAccuracy: 3, updateDistance: 10, minimumUpdateTime : 1000 * 20}); // should update every 20 sec according to google documentation this is not so sure.
}
exports.buttonStartTap = buttonStartTap;

function buttonStopTap() {
	if (watchId) {
		geolocation.clearWatch(watchId);
	}
}
exports.buttonStopTap = buttonStopTap;

{% endnativescript %} {% angular %}

<StackLayout>
    <Button row="2" text="start monitoring" (tap)="buttonStartTap()"></Button>
    <Button row="3" text="stop monitoring" (tap)="buttonStopTap()"></Button>
</StackLayout>

{% endangular %}

{% nativescript %}export function {% endnativescript %}public {% angular %}{% endangular %}buttonStartTap() {
	watchId = watchLocation(
	function (loc) {
		if (loc) {
			console.log("Received location: " + loc);
		}
	}, 
	function(e){
		console.log("Error: " + e.message);
	}, 
	{desiredAccuracy: 3, updateDistance: 10, minimumUpdateTime : 1000 * 20}); // Should update every 20 seconds according to Googe documentation. Not verified.
}

{% nativescript %}export function {% endnativescript %}public {% angular %}{% endangular %}buttonStopTap() {
	if (watchId) {
		clearWatch(watchId);
	}
}

distance

This method lets you measure the distance between two locations in meters.

Example 4: How to get distance between to too location

{% nativescript %}

function getDistance(loc1, loc2) {
    console.log("Distance between loc1 and loc2 is: " + geolocation.distance(loc1, loc2));
}

{% endnativescript %}

function getDistance(loc1, loc2) {
    console.log("Distance between loc1 and loc2 is: " + distance(loc1, loc2));
}

See Also