Giter Site home page Giter Site logo

timfpark / react-native-location Goto Github PK

View Code? Open in Web Editor NEW
875.0 15.0 204.0 5.01 MB

React Native plug-in that provides GPS location information

License: MIT License

Objective-C 13.49% JavaScript 34.26% Java 25.19% TypeScript 23.56% Ruby 0.58% Starlark 2.93%

react-native-location's Introduction

react-native-location

MIT License Supports Android and iOS Supports React Native >= 0.46 CircleCI Status

Native GPS location support for React Native. You might decide to use this library over the built-in geolocation because it includes some additional features:

  • Allows you choose what type of permission to ask for ("when in use" or "always"). The built-in geolocation library will look at your plist file and choose "always" if you have the NSLocationAlwaysUsageDescription property, however, you might have a usecase where you want to start by asking the user for "while in use" permission and later upgrade the permission to "always" when they turn on a feature which requires background location.
  • Ability to check the current permission status (RNLocation.getCurrentPermission).
  • Allows you to monitor the device heading.

Installation

Install the library using either Yarn:

yarn add react-native-location

or using npm:

npm install --save react-native-location

You then need to link the native parts of the library for the platforms you are using. Click on the arrow to show the steps for each platform.

iOS Installation Instructions

1a. Automatically link with the CLI tool

The easiest way to link the library is using the CLI tool by running this command from the root of your project:

react-native link react-native-location

1b. Install with Cocoapods

You can also link the library using Cocoapods by adding this line to your Podfile:

pod 'react-native-location', :path => '../node_modules/react-native-location/react-native-location.podspec'

1c. Or manually link the library

If you can't or don't want to use the CLI tool, you can also manually link the library using the intructions in the React NAtive documentation.

2. Ensure you have the CoreLocation library linked

This is not required if you have installed using Cocoapods.

You then need to make sure you have the iOS CoreLocation library linked to your project.

To do this, click on the your project in XCode (the name of your project at the top of the left panel), select your apps build target, go to the Build Phases tab then in the Link Binary With Libraries section add CoreLocation.framework.

3. Info.plist usage descriptions

Finally, you then need to make sure you have the correct usage discriptions inside your Info.plist file. The message will show in the Alert box when your app requests permissions and lets the user know why you are asking for that permissions. They are also part of the App Store review process.

If you are only requesting "when in use" (foreground) location access you just need to make sure you have the NSLocationWhenInUseUsageDescription item in your Plist.

If you are requesting "always" (background) permission you will also need to add NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationAlwaysUsageDescription into your PList file.

The easiest way to add these is to find your Info.plist in Xcode, right click on it, and then choose "edit as source code". You can then enter the items you need into the file:

<key>NSLocationWhenInUseUsageDescription</key>
<string>This is the plist item for NSLocationWhenInUseUsageDescription</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This is the plist item for NSLocationAlwaysAndWhenInUseUsageDescription</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This is the plist item for NSLocationAlwaysUsageDescription</string>

4. Background mode setup (optional)

For background location to work, a few things need to be configured:

  1. In the Xcode project, go to Capabilities, switch on "Background Modes" and check "Location updates".
  2. Set NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationAlwaysUsageDescription in your Info.plist file.
  3. For iOS 9+, set allowsBackgroundLocationUpdates to true when configuring the library in your Javascript code. Like this:
RNLocation.configure({ allowsBackgroundLocationUpdates: true });
Android Installation Instructions

1a. Automatically link the library using the CLI tool

The easiest way to link the library is using the CLI tool by running this command from the root of your project:

react-native link react-native-location

1b. Manually link the library

If you can't or don't want to use the CLI tool, you can manually link the library by making the following changes (click on the arrow to show the steps):

Steps to manually link the library

android/settings.gradle

include ':react-native-location'
project(':react-native-location').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-location/android')

android/app/build.gradle

dependencies {
   ...
   implementation project(':react-native-location')
}

android/app/src/main/.../MainApplication.java

On top, where imports are:

import com.github.reactnativecommunity.location.RNLocationPackage;

Add the RNLocationPackage class to your list of exported packages.

@Override
protected List<ReactPackage> getPackages() {
    return Arrays.asList(
            new MainReactPackage(),
            new RNLocationPackage()
    );
}

2. Android manifest permissions

You need to ensure that your AndroidManifest.xml contains this line:

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

If you want to access fine location then you should also include:

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

3. Install the Google Fused Location provider dependency (optional)

The library provides two methods of getting the location on Android. The default is the builtin location manager, however, you can optionally choose to install the Fused Location library which provides more accurate and faster results. The downside is that it will only work on devices with Google Play Services installed and configured (which is most Android devices in the west, but not Kindle devices or Asian markets).

If you would like to use the Google Play Services Fused Location provider, then you need to add these dependencies to your android/app/build.gradle file:

implementation "com.google.android.gms:play-services-base:16.0.1"
implementation "com.google.android.gms:play-services-location:16.0.0"

Example application

In the example folder is a React Native sample app which you can use as a sample implementation to start from.

The app requests permissions, takes reading every 5 distance and starts immediately. To use in the iOS simulator, look on the Debug -> Location menu for sample trips that will show you updating location such as City Bycicle Ride, City Run, and Freeway Drive.

Example App

Usage

import RNLocation from 'react-native-location';

RNLocation.configure({
  distanceFilter: 5.0
})

RNLocation.requestPermission({
  ios: "whenInUse",
  android: {
    detail: "coarse"
  }
}).then(granted => {
    if (granted) {
      this.locationSubscription = RNLocation.subscribeToLocationUpdates(locations => {
        /* Example location returned
        {
          speed: -1,
          longitude: -0.1337,
          latitude: 51.50998,
          accuracy: 5,
          heading: -1,
          altitude: 0,
          altitudeAccuracy: -1
          floor: 0
          timestamp: 1446007304457.029,
          fromMockProvider: false
        }
        */
      })
    }
  })

Methods

To access the methods, you need import the react-native-location module. This is done through import RNLocation from 'react-native-location'.

Configuration

RNLocation.configure

This is used to configure the location provider. You can use this to enable background mode, filter location updates to a certain distance change, and ensure you have the power settings set correctly for your use case.

You can call configure multiple times at it will only change the setting which you pass to it. For example if you only want to change activityType, you can call configure with just that property present.

RNLocation.configure({
    distanceFilter: 100, // Meters
    desiredAccuracy: {
      ios: "best",
      android: "balancedPowerAccuracy"
    },
    // Android only
    androidProvider: "auto",
    interval: 5000, // Milliseconds
    fastestInterval: 10000, // Milliseconds
    maxWaitTime: 5000, // Milliseconds
    // iOS Only
    activityType: "other",
    allowsBackgroundLocationUpdates: false,
    headingFilter: 1, // Degrees
    headingOrientation: "portrait",
    pausesLocationUpdatesAutomatically: false,
    showsBackgroundLocationIndicator: false,
})

There are the valid configuration options and what they do:

Option Platforms Description Values Documentation
distanceFilter Android iOS The minimum distance in meters that the device location needs to change before the location update callback in your app is called. Defaults to 0 for no filtering. number Android Docs Apple Docs
desiredAccuracy Android iOS

The accuracy of the location data. Defaults to best on iOS and balancedPowerAccuracy on Android.

Valid options for android: balancedPowerAccuracy, highAccuracy, lowPower, or noPower.

Valid options for ios: bestForNavigation, best, nearestTenMeters, hundredMeters, or threeKilometers.

{ android: string, ios: string } Android Docs Apple Docs
androidProvider Android The provider which is used on Android to get the location. Your app must include the Google Play services dependencies to use the playServices location provider. By default it will choose the playServices location provider if it detects that the dependencies are installed, otherwise, it will use the standard Android version which does not require Google Play Services to be installed. Note that auto only checks that the dependencies are installed, not that the user has the Google Play services APK installed and set up correctly. "auto", "playServices", or "standard"
interval Android

Set the desired interval for active location updates, in milliseconds.

The location client will actively try to obtain location updates for your application at this interval, so it has a direct influence on the amount of power used by your application. Choose your interval wisely.

This interval is inexact. You may not receive updates at all (if no location sources are available), or you may receive them slower than requested. You may also receive them faster than requested (if other applications are requesting location at a faster interval).

number Android Docs
fastestInterval Android

Explicitly set the fastest interval for location updates, in milliseconds.

This controls the fastest rate at which your application will receive location updates, which might be faster than `interval` in some situations (for example, if other applications are triggering location updates).

This allows your application to passively acquire locations at a rate faster than it actively acquires locations, saving power.

By default this is 6x the `interval`.

number Android Docs
maxWaitTime Android

Sets the maximum wait time in milliseconds for location updates.

If you pass a value at least 2x larger than the interval specified with setInterval(long), then location delivery may be delayed and multiple locations can be delivered at once.

number Android Docs
allowsBackgroundLocationUpdates iOS A Boolean value indicating whether the app should receive location updates when suspended. Requires permissions to always access the users location. Defaults to false. boolean Apple Docs
activityType iOS The type of user activity associated with the location updates. Defaults to other. "other", "automotiveNavigation", "fitness", "otherNavigation", or "airborne" Apple Docs
headingFilter iOS The minimum angle in degrees that the device heading needs to change before the heading update callback in your app is called. Defaults to 0 for no filtering. number
headingOrientation iOS The device orientation to use when computing heading values. Defaults to portrait. "portrait", "portraitUpsideDown", "landscapeLeft", or "landscapeRight" Apple Docs
pausesLocationUpdatesAutomatically iOS A Boolean value indicating whether the location manager object may pause location updates. Defaults to true. boolean Apple Docs
showsBackgroundLocationIndicator iOS A Boolean indicating whether the status bar changes its appearance when location services are used in the background. Defaults to false. Only works on iOS 11+ and is ignored for earlier versions of iOS. boolean Apple Docs

Permissions

Correctly managing permissions is key to working with the users location in mobile apps.

  • Ask for the lowest level of permissions you can. You'll almost always only need whenInUse (foreground) permission rather than background.
  • On iOS you only get one chance to ask for permission. If the user requests it the first time this method will always resolves to false.
  • If you ask for always permission then the user gets the chance to accept, but only give you whenInUse permission. The Promise will still resolve to false, however, if you call RNLocation.getCurrentPermission you can check if they actually accepted the lesser permission.
  • You should monitor the permissions and respond to it correctly. The user is able to go to their phone setting and revoke or downgrade permissions at any time.

RNLocation.requestPermission

This method should be called before subscribing to location updates. You need to pass in the type of permission you want for each platform. You can choose not to ignore a platform and it will be ignored. The method returns a promise which resolves to true if the permission was granted and false if not. For Android you can optionally provide a rationale which will be displayed if you ask the user for permission a 2nd time after they have denied permission once.

RNLocation.requestPermission({
  ios: 'whenInUse', // or 'always'
  android: {
    detail: 'coarse', // or 'fine'
    rationale: {
      title: "We need to access your location",
      message: "We use your location to show where you are on the map",
      buttonPositive: "OK",
      buttonNegative: "Cancel"
    }
  }
});

RNLocation.checkPermission

Checks if the currently granted permissions match the given options. You can call this before requestPermission to check if you already have the permission level you would like. This is especially useful if you want to display a message to the user about not having the correct permissions before actually requesting them.

RNLocation.checkPermission({
  ios: 'whenInUse', // or 'always'
  android: {
    detail: 'coarse' // or 'fine'
  }
});

RNLocation.getCurrentPermission

Gets the current permission status. Note that the values will be different on Android and iOS as the permission systems are different. It's usually best to use RNLocation.checkPermission instead of checking the permission status yourself to avoid re-implementing the logic.

RNLocation.getCurrentPermission()
  .then(currentPermission => {
    ...
  })

RNLocation.subscribeToPermissionUpdates

Monitor the permission status for changes.

// Subscribe
const unsubscribe = RNLocation.subscribeToPermissionUpdates(currentPermission => {
  ...
})

// Unsubscribe
unsubscribe();

RNLocation.subscribeToLocationUpdates

Subscribe to location changes with the given listener. Ensure you have the correct permission before calling this method. The location provider will respect the settings you have given it. Each event may return an array with more than one location. This is because the OS might batch location updates together and deliver them all at once. Take a look at the timestamp to find the latest.

// Subscribe
const unsubscribe = RNLocation.subscribeToLocationUpdates(locations => {
  ...
})

// Unsubscribe
unsubscribe();

RNLocation.getLatestLocation

Get the latest location. Ensure you have the correct permission before calling this method.

This will subscribe to location events for you at the unsubscribe when it gets its first valid location. Usually, this method will return very fast with a possibly out of date location, however, in some circumstances it will not return a location. Therefore, this method has a timeout after which the promise will be resovled with null value.

The location provider will respect the settings you have given it, so if you need a location with a certain accuracy, ensure you call RNLocation.configure first. If you want any location then ensure you call RNLocation.configure with no distance filter.

RNLocation.configure({ distanceFilter: null });
RNLocation.getLatestLocation({ timeout: 60000 })
  .then(latestLocation => {
    // Use the location here
  })

RNLocation.subscribeToSignificantLocationUpdates (iOS only)

Subscribe to significant updates to the users location with the given listener. This method does not take into account the distanceFilter which you configured RNLocation with. In most cases, you should call RNLocation.configure with the correct settings and then use RNLocation.subscribeToLocationUpdates to subscribe to the location updates. This will allow you to support both Android and iOS with the same code. For more details, take a look at Apple's documentation.

// Subscribe
const unsubscribe = RNLocation.subscribeToSignificantLocationUpdates(locations => {
  ...
})

// Unsubscribe
unsubscribe();

RNLocation.subscribeToHeadingUpdates (iOS only)

Subscribe to heading changes with the given listener. Ensure you have the correct permission before calling this method. The location provider will respect the settings you have given it.

// Subscribe
const unsubscribe = RNLocation.subscribeToHeadingUpdates(heading => {
  ...
})

// Unsubscribe
unsubscribe();

License

The library is released under the MIT licence. For more information see LICENSE.

react-native-location's People

Contributors

ace68723 avatar alienxp03 avatar bugsbunny338 avatar butuzgol avatar caledhwa avatar dependabot[bot] avatar frizzonelli avatar heroic avatar janicduplessis avatar jlc467 avatar kicktheken avatar matt-oakes avatar mischkew avatar nicinabox avatar osman-masood avatar tgevaert avatar timfpark avatar tkuenzle 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

react-native-location's Issues

Working towards 1.0.0 - Library stability

I believe this could be a very useful library for the React Native community and I'd like to thank @timfpark for granting me push access to this repository to help with maintenance.

This issue will be a todo list for how we can get the library to a point where it is usable out of the box again. In the future, I will post another issue which includes some post 1.0.0 goals which I think would make this library even more useful. The goal for now is to make which is currently here more stable.

  • Support the latest version of React Native: To do this we need to update the imports which the native code uses as mentioned in a few comments in the issues (#35 (comment)).
  • Ensure the API is stable and well documented: There is currently an open pull request which changes the way that events are handled. We should look into making this change, if needed, and ensure that the API we do have is well documented and is in a place where we can make changes in the future without requiring breaking changes.
  • Typings: We should ensure that the library has well-defined types that work with both Flow and TypeScript. This should make developing with the library much nicer.
  • Update the README: We should make it clear that currently the library only supports iOS. We should also make it clearer that you need to ensure you have the correct PList entries to get the library to work on iOS 11+. I also believe that the README needs to mention why it a better solution than using the build in Geolocation methods (as noted in #24 and other issues).

As I said, this is just a start and hopefully we can make this library something even more useful in the future.

Post here if you have any comments or requests.

Not Work background in Android

I do not work in background on Android I leave the App in the background stop sending the location even if I have locked the device, in iOS everything works ok.
My configure:
"react-native": "0.57.8"

RNLocation.configure({
distanceFilter: 5.0, // Meters
desiredAccuracy: {
ios: "best",
android: "highAccuracy"
},
// Android only
androidProvider: "auto",
interval: 5000, // Milliseconds
fastestInterval: 10000, // Milliseconds
maxWaitTime: 5000, // Milliseconds
// iOS Only
activityType: "other",
allowsBackgroundLocationUpdates: true,
headingFilter: 1, // Degrees
headingOrientation: "portrait",
pausesLocationUpdatesAutomatically: false,
showsBackgroundLocationIndicator: false,
})
RNLocation.requestPermission({
ios: "always",
android: {
detail: "fine",
rationale: {
title: "Can we access your location?",
message: "Lokate would like to use your location to show you people within a 50 ft distance , that are on the same places as you and if the match is done you can start being friends and chatting. Enter your device settings and change the button of the apps location to allways allow. Close and restart the app again.",
buttonPositive: "OK",
buttonNegative: "Cancel"
}
}
})

Request location manually

Hello,

I like this project and we are using it without any issues.

Currently, we are heading a situation where we don't want to have an automatically updated location every time it is changed.
But we want to make it manually on specific situations (screen loaded, etc) because every time is location updated and stored into redux, some "ugly" rerendering is made. We should increase distanceFilter or compare values in component lifetime cycle method. But it is so clean as should be.

In this package core is some undocumented methods to automatically starting and stopping location updates.

Maybe startUpdatingLocation and stopUpdatingLocation should be documented. But still, need to be implemented a trigger to get location manually. And after all, option to enable or disable automatic updating location when RNLocation is configured.

iOS: https://developer.apple.com/documentation/corelocation/cllocationmanager/1620548-requestlocation?language=objc
Android: https://developer.android.com/reference/android/location/LocationManager.html#requestSingleUpdate(java.lang.String,%2520android.location.LocationListener,%2520android.os.Looper)

Take this issue just like a discussion for the feature request.

How to open location service settings?

Hi,
I found the issue when my app is turn of location service in the settings panel. I have allowed location permission. However, I was turned off my device location service. So the location always null.

How can i check the location settings and open settings panel to user turn on?

Thanks

Get Current Location

How to get the current location?
subscribeToSignificantLocationUpdates will only fire if there is a change in location, what if I just want the current location.
I didn't see any method for that in the documentation.

subscribeToLocationUpdates() rarely returns new locations on Android

On Android, subscribeToLocationUpdates() returns a set of locations the first time it's called, but after that, it sends a new locations array extremely infrequently - on the order of once every 10 minutes (even if moving significantly). Fine location access is authorized.

On iOS, the method works as expected (using the same code below).

Relevant code is below. Are there any other settings I can adjust?

RNLocation.configure({
  distanceFilter: null, // have tried 0, 1, 10, 100
  desiredAccuracy: {
    ios: 'best',
    android: 'highAccuracy'
  }
});
unsubscribe = RNLocation.subscribeToLocationUpdates((locations) => {
  Alert.alert('locations', JSON.stringify(locations));
});

Build tools error, cannot find symbol

cannot find symbol
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
^
symbol: variable O
location: class VERSION_CODES

I guess the build tools version is old

I get sometimes error: "Attempt to invoke virtual method 'android.os.Looper"

java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.app.Activity.getMainLooper()' on a null object reference
at com.google.android.gms.common.api.GoogleApi.(Unknown Source:50)
at com.google.android.gms.location.FusedLocationProviderClient.(Unknown Source:8)
at com.google.android.gms.location.LocationServices.getFusedLocationProviderClient(Unknown Source:2)
at com.github.reactnativecommunity.location.RNPlayServicesLocationProvider.(RNPlayServicesLocationProvider.java:49)
at com.github.reactnativecommunity.location.RNLocationModule.createPlayServicesLocationProvider(RNLocationModule.java:103)
at com.github.reactnativecommunity.location.RNLocationModule.createDefaultLocationProvider(RNLocationModule.java:96)
at com.github.reactnativecommunity.location.RNLocationModule.configure(RNLocationModule.java:39)
at java.lang.reflect.Method.invoke(Native Method)
at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158)
at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
at android.os.Looper.loop(Looper.java:164)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:192)
at java.lang.Thread.run(Thread.java:764)

And then the app is closed

Docs require via NativeModules instead of require('react-native-location')

Great library. This has been super useful to me.

I'm still a bit of a react-native newbie, but I was wondering if there's a reason why docs have us get Location via

var { RNLocation: Location } = require('NativeModules');

instead of

var Location = require('react-native-location');

The second approach seems both more clear, and allows me to mock this more easily in jest, i.e.

jest.mock('react-native-location', () => ({
  requestAlwaysAuthorization() {},
  startUpdatingLocation() {}
  // etc
})) ;

Location Service Status

I get authorization = "denied" for new installed app but with location service disabled!
shouldn't i get "not determined" status??!?!
or
how should i get location service status from your package?!

GPS Strength

It could be better if we do have gps strength level

Could not resolve project :react-native-location

Getting this error after manually linking on Android:

ERROR: Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve project :react-native-location.
Show Details
Affected Modules: app


ERROR: Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath': Could not resolve project :react-native-location.
Show Details
Affected Modules: app


ERROR: Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve project :react-native-location.
Show Details
Affected Modules: app


ERROR: Unable to resolve dependency for ':app@release/compileClasspath': Could not resolve project :react-native-location.
Show Details
Affected Modules: app


ERROR: Unable to resolve dependency for ':app@releaseUnitTest/compileClasspath': Could not resolve project :react-native-location.
Show Details
Affected Modules: app

accuracy always 2000

When I try to get my location ,the accuracy value that I obtained is always 2000, it never changed. Is there any bugs have to be fixed or I am doing wrong somethink ?

APK

Hi, do you have an APK file? I'd like to test the example. Thanks!

subscribeToPermissionUpdates not working on Android

Hi guys

First of all, thanks for this amazing library! It really helped us tackle a number of difficult problems.

One thing, however, that I don't seem to get working is, subscribeToPermissionUpdates on Android. It seems as though it is never being called.

Beyond that, the library works great on Android and I am pretty sure I installed it correctly.

I am using:

react-native 0.59.5
react-native-location: 2.2.0

undefined is not an object (evaluating '_NativeModules.RNLocation.requestAlwaysAuthorization')

I do the npm install --save react-native-location ,and react-native link
this is my code , it alert me that undefined is not an object

import React,{Component} from 'react';
import {
    View,
    Text,
    StyleSheet,
    DeviceEventEmitter,
    Dimensions,
} from 'react-native';


import { RNLocation as Location } from 'NativeModules';

Location.requestAlwaysAuthorization();
Location.startUpdatingLocation();
Location.setDistanceFilter(5.0);

export default class RNLocationTest extends Component {


    componentWillMount() {

        Location.requestAlwaysAuthorization();
        Location.startUpdatingLocation();
        Location.setDistanceFilter(5.0);

        DeviceEventEmitter.addListener('locationUpdated', (location) => {
            console.log('^^^^^^^^^^',location);
        })
    }


    render (){
        return (
          <View style={styles.container}>
              <Text>Test location</Text>
          </View>
        );
    }

}

Native module cannot be null

Thanks for this library, it works good with android but with iOS it gives Native Module cannot be null error.

Things I did:

  1. Installed the lib.
  2. linked using react-native link
  3. even linked location.coreframework lib

can someone help?

Support for iOS 11

Will this library be updated to support iOS 11?

Running in iOS 11 currently and apparently no location data is recorded.

react-native: 0.44.0
react-native-location: 0.27.0

Blue ticker IOS for location tracking remove/ stop location tracking based on premission.

I need to track location only when user allows "Always" permission for location tracking. The same functionality as Foursquare app.
The problem is as long as the permission for location tracking is always there is no ticker for location tracking in IOS. When I change permission to "when in use" from settings the ticker start showing. Here I want that the location tracking stops and blue ticker goes away

Possible Unhandled Promise Rejection

Trying to solve an issue I am having with this otherwise great library! On Android I am getting the following warning:

Possible Unhandled Promise Rejection (id: 0) 
Error: Error configuring react-native-location

This occurs on my Android device after I have agreed to all permissions, but turn off my location services / GPS. I can check if GPS is enabled with another library, however I do like the in-app pop up asking the user to turn GPS back on. This dialog is triggered when I run RNLocation.configure however if you cancel / decline the dialog RNLocation.configure triggers the above warning.

errors with react-native 0.44.0

setup a clean project

{
"name": "NatLoc",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.0.0-alpha.6",
"react-native": "0.44.0",
"react-native-location": "^0.27.0"
},
"devDependencies": {
"babel-jest": "20.0.1",
"babel-preset-react-native": "1.9.2",
"jest": "20.0.1",
"react-test-renderer": "16.0.0-alpha.6"
},
"jest": {
"preset": "react-native"
}
}

installed react-native-location
linked
and compile in xcode
gives errors (just showing a few)

../react-native/React/Base/RCTBridge.h:66:12: note: previous definition is here
@interface RCTBridge : NSObject
^
^
@Property (nonatomic, copy, readonly) NSArray *moduleClasses;
^
: error: property has a previous declaration
@Property (nonatomic, strong, readonly) NSURL *bundleURL;
^
error: property has a previous declaration
@Property (nonatomic, strong) Class executorClass;
^
In file included from /Users/pierrejean/Dropbox/dev-app/NatLoc/node_modules/react-native-location/RNLocation.m:3:
../react-native/React/Base/RCTBridge.h:166:37: note: property declared here
@Property (nonatomic, strong) Class executorClass;
^
error: property has a previous declaration
@Property (nonatomic, weak, readonly) id delegate;
^
error: property has a previous declaration
@Property (nonatomic, copy, readonly) NSDictionary *launchOptions;
^
error: property has a previous declaration
@Property (nonatomic, readonly, getter=isLoading) BOOL loading;
^
error: property has a previous declaration
@Property (nonatomic, readonly, getter=isValid) BOOL valid;
^
error: property has a previous declaration
@Property (nonatomic, readonly, weak) JSContext *jsContext;
^
error: property has a previous declaration
@Property (nonatomic, readonly, strong) RCTPerformanceLogger *performanceLogger;
^

^
4 warnings and 10 errors generated.

Build failed 2017-05-14, 12:50 PM

Crash after requestPermission on Emulator Android Q

My setup:
"react-native": "0.59.8"
"react-native-location": "^2.2.0"
"react-native-router-flux": "^4.1.0-beta.5"

after clicking allow or refuse permission on the permission dialog in emulator android Q, the app will crash
but it works fine on lower android version,
maybe we can check if something has changed on Q that the library need to handle?
or maybe just the Q on emulator is still not so stable?
any thoughts?

NativeModule syntax no longer valid?

I'm unable to build this in it's current state, with RN 0.14.0. I get:

bundle: Created ReactPackager
uncaught error Error: UnableToResolveError: Unable to resolve module NativeModules from {MY_PROJECT_PATH}/node_modules/react-native-location/RNLocation.ios.js: Invalid directory /Users/node_modules/NativeModules

When changing this line:

var NativeRNLocation = require('NativeModules').RNLocation;

to this:

var NativeRNLocation = require('react-native').NativeModules.RNLocation;

Things start working again. It seems vaguely related to this.

Implementation in Android

Hello,

is there any implementation with Android and Ios support? Are anyone working on this or the implementation still propesed?

Thanks!

Can't get the location from 'getLatestLocation'

This is my code to get the last location:

RNLocation.requestPermission({
      ios: "whenInUse",
      android: {
        detail: "coarse"
      },
    }).then(granted => {
      if (granted) {
        RNLocation.configure({
          distanceFilter: 0, // Meters
        });
        RNLocation.getLatestLocation({ timeout: 60000 }).then(locations => {
          if (locations != null) {
            global.longitude = locations.longitude;
            global.latitude = locations.latitude;
            callback(locations);
          }
        });
      }
    });

the locations is null,
also I want to know that how to request the Permission('coarse' and 'fine') simultaneously

Trying to test in background

On simulator background works find but on device I puts console.logs but they not triggered
May you can help me ?

Can you add the values of 'location' to the README?

I'm looking at this right now and it's unclear what "location" returns. Can you add that to the README?

For example, is it 'latitude' and 'longitude'? Is there a city name? Is it this data? https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocation_Class/

Specifically this part of the README could be improved:

var subscription = DeviceEventEmitter.addListener(
    'locationUpdated',
    (location) => {
        /**
          Location will be of the form:
          {'lat': ..., 'long': ..., etc}
    }
);

startMonitoringSignificantLocationChanges is not a function

I'm getting error TypeError: this.nativeInterface.startMonitoringSignificantLocationChanges is not a function

Version:
react-native: 0.57.1
react-native-location: ^2.1.1

Screenshot:
screenshot_1549958479

Stack trace:

TypeError: TypeError: this.nativeInterface.startMonitoringSignificantLocationChanges is not a function. (In 'this.nativeInterface.startMonitoringSignificantLocationChanges()', 'this.nativeInterface.startMonitoringSignificantLocationChanges' is undefined)

This error is located at:
    in HomeScreen (created by SceneView)
    in SceneView (at StackViewLayout.js:784)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in AnimatedComponent (at StackViewCard.js:69)
    in RCTView (at View.js:44)
    in AnimatedComponent (at screens.native.js:59)
    in Screen (at StackViewCard.js:57)
    in Card (at createPointerEventsContainer.js:27)
    in Container (at StackViewLayout.js:860)
    in RCTView (at View.js:44)
    in ScreenContainer (at StackViewLayout.js:311)
    in RCTView (at View.js:44)
    in AnimatedComponent (at StackViewLayout.js:307)
    in Handler (at StackViewLayout.js:300)
    in StackViewLayout (at withOrientation.js:30)
    in withOrientation (at StackView.js:79)
    in RCTView (at View.js:44)
    in Transitioner (at StackView.js:22)
    in StackView (created by Navigator)
    in Navigator (at createKeyboardAwareNavigator.js:12)
    in KeyboardAwareNavigator (created by SceneView)
    in SceneView (at createTabNavigator.js:39)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in ResourceSavingScene (at createBottomTabNavigator.js:113)
    in RCTView (at View.js:44)
    in ScreenContainer (at createBottomTabNavigator.js:103)
    in RCTView (at View.js:44)
    in TabNavigationView (at createTabNavigator.js:197)
    in NavigationView (created by Navigator)
    in Navigator (created by SceneView)
    in SceneView (created by SwitchView)
    in SwitchView (created by Navigator)
    in Navigator (at createAppContainer.js:388)
    in NavigationContainer (at renderApplication.js:34)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in AppContainer (at renderApplication.js:33)

This error is located at:
    in NavigationContainer (at renderApplication.js:34)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in AppContainer (at renderApplication.js:33)
subscribeToSignificantLocationUpdates
    subscriptions.js:44:8
componentDidMount
    index.js:45:6
wrapper
    native.js:486:32
fn
    native.js:507:23
commitLifeCycles
    ReactNativeRenderer-dev.js:12144:10
commitAllLifeCycles
    ReactNativeRenderer-dev.js:13496:8
invokeGuardedCallbackImpl
    ReactNativeRenderer-dev.js:92:15
invokeGuardedCallback
    ReactNativeRenderer-dev.js:306:36
commitRoot
    ReactNativeRenderer-dev.js:13702:8
completeRoot
    ReactNativeRenderer-dev.js:15269:13
performWorkOnRoot
    ReactNativeRenderer-dev.js:15197:21
performWork
    ReactNativeRenderer-dev.js:15090:24
performSyncWork
    ReactNativeRenderer-dev.js:15047:14
requestWork
    ReactNativeRenderer-dev.js:14925:19
scheduleWork
    ReactNativeRenderer-dev.js:14711:16
scheduleRootUpdate
    ReactNativeRenderer-dev.js:15429:15
render
    ReactNativeRenderer-dev.js:16142:20
renderApplication
    renderApplication.js:59:34
run
    AppRegistry.js:101:10
runApplication
    AppRegistry.js:195:26
__callFunction
    MessageQueue.js:349:47
<unknown>
    MessageQueue.js:106:26
__guard
    MessageQueue.js:297:10
callFunctionReturnFlushedQueue
    MessageQueue.js:105:17

subscribeToLocationUpdates can't get result

RNLocation.configure({
distanceFilter: 5.0
})

RNLocation.requestPermission({
ios: "whenInUse",
android: {
detail: "coarse"
}
}).then(granted => {
if (granted) {
console.log("granted")
this.locationSubscription = RNLocation.subscribeToLocationUpdates(locations => {
console.log("获取位置",locations)
/* Example location returned
{
speed: -1,
longitude: -0.1337,
latitude: 51.50998,
accuracy: 5,
heading: -1,
altitude: 0,
altitudeAccuracy: -1
floor: 0
timestamp: 1446007304457.029
}
*/
})
console.log("granted1")
}
})

RNLocation.subscribeToLocationUpdates can't get locations?

Duplicate interface definition for class 'RCTBridge'

After doing react-native link I get in xcode the following compilation error:

Duplicate interface definition for class RCTBridge

If I remove the following line from RNLocation.m it works:
#import "RCTBridge.h"

I am using react native version 0.41.2. Could it be related to this version?

Usage Question

@matt-oakes first of all thanks for your work :)

Now the question, We just need to get the location when the user use a specific feature of the App, so in that moment we need to get the location and then stop the updating process, so do you think this apporach is good in order to do that and saving phone battery?


RNLocation.requestPermission({
      ios: "whenInUse",
      android: {
        detail: "fine",
        rationale: {
          title: "Location permission",
          message: "We use your location to demo the library",
          buttonPositive: "OK",
          buttonNegative: "Cancel"
        }
      }
    }).then(granted => {
      if (granted) {
        this._startUpdatingLocation();
      }
    });
  }

  _startUpdatingLocation = () => {
    this.locationSubscription = RNLocation.subscribeToLocationUpdates(
      locations => {
        this.setState({ location: locations[0] });
      this._stopUpdatingLocation();  // this was added to stop once I get the location
      }
    );
  };

  _stopUpdatingLocation = () => {
    this.locationSubscription && this.locationSubscription();
   // this.setState({ location: null });  // this was removed for not loose the location
  };

Thanks!

Installation Bug on IOS CocoaPod

Hi,

I have this error: React/RCTBridge.h' file not found

it works on Android, I tried cocoapods without react-native link and with it, just in case, none of them works.

Any help?

Thanks.

TypeError in getLatestLocation locations.sort

Hello,

I'm looking into using this library in my Android project. I'm getting an exception in getLatestLocation when there is more than one location being returned by subscribeToLocationUpdates. The sort function is treating the location.timestamp property as a Date object, but when I inspect it in my debugger, it is simply a number type:

accuracy: 12.479999542236328
altitude: 5
altitudeAccuracy: 40
course: 0
courseAccuracy: 0
latitude: 37.4219983
longitude: -122.084
speed: 0
speedAccuracy: 0
timestamp: 1555098489000

Your Simple example not working in android

import RNLocation from 'react-native-location';

RNLocation.configure({
distanceFilter: 5.0
})

RNLocation.requestPermission({
ios: "whenInUse",
android: {
detail: "coarse"
}
}).then(granted => {
if (granted) {
this.locationSubscription = RNLocation.subscribeToLocationUpdates(locations => {
console.log('locations',locations);
/* Example location returned
{
speed: -1,
longitude: -0.1337,
latitude: 51.50998,
accuracy: 5,
heading: -1,
altitude: 0,
altitudeAccuracy: -1
floor: 0
timestamp: 1446007304457.029
}
*/
})
}
})

The command line "console.log('locations',locations);", called just once when init it.
When i tried to change location i do not get the new location.

Ios - working perfectly
Tested on latest version.

React Native v.0.13.1: Error building DepdendencyGraph

While updating my app to latest React Native 0.13.1 I run into following error:

Error building DepdendencyGraph:
 Error: Naming collision detected: {project-folder}/node_modules/react-native/node_modules/react-tools/src/renderers/shared/event/eventPlugins/ResponderTouchHistoryStore.js collides with {project-folder}/node_modules/react-native-location/node_modules/react-native/node_modules/react-tools/src/renderers/shared/event/eventPlugins/ResponderTouchHistoryStore.js
    at HasteMap._updateHasteMap ({project-folder}/node_modules/react-native/packager/react-packager/src/DependencyResolver/DependencyGraph/HasteMap.js:123:13)
    at {project-folder}/node_modules/react-native/packager/react-packager/src/DependencyResolver/DependencyGraph/HasteMap.js:95:28
    at tryCallOne ({project-folder}/node_modules/react-native/node_modules/promise/lib/core.js:37:12)
    at {project-folder}/node_modules/react-native/node_modules/promise/lib/core.js:103:15
    at flush ({project-folder}/node_modules/react-native/node_modules/promise/node_modules/asap/raw.js:50:29)
    at doNTCallback0 (node.js:407:9)
    at process._tickCallback (node.js:336:13)

Removing react-native folder in /node_modules/react-native-location/node_modules/ does fix this error.

Or could you update the dependency to react-native-location to latest RN ^0.13.1, please?

[EDIT]
Using peerDependencies might be helpful, too:

// package.json
"peerDependencies": {
    "react-native": ">=0.12"
}

[/EDIT]

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.