├── .eslintrc.js ├── .gitignore ├── .markdownlint.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── android ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── github │ └── amarcruz │ └── geolocation │ ├── Constants.java │ ├── LocationOptions.java │ ├── LocationResolver.java │ ├── PositionError.java │ ├── RNGeolocationModule.java │ ├── RNGeolocationPackage.java │ └── SingleLocationRequest.java ├── geoloc.js ├── index.d.ts ├── index.js ├── index.js.flow ├── package.json └── yarn.lock /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parserOptions: { 4 | ecmaVersion: 2016, 5 | sourceType: 'module', 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # node-waf configuration 17 | .lock-wscript 18 | 19 | # Compiled binary addons (http://nodejs.org/api/addons.html) 20 | build/Release 21 | 22 | # Dependency directory 23 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 24 | node_modules 25 | npm-debug.log 26 | 27 | # OSX 28 | # 29 | .DS_Store 30 | 31 | # Xcode 32 | # 33 | build/ 34 | *.pbxuser 35 | !default.pbxuser 36 | *.mode1v3 37 | !default.mode1v3 38 | *.mode2v3 39 | !default.mode2v3 40 | *.perspectivev3 41 | !default.perspectivev3 42 | xcuserdata 43 | *.xccheckout 44 | *.moved-aside 45 | DerivedData 46 | *.hmap 47 | *.ipa 48 | *.xcuserstate 49 | project.xcworkspace 50 | 51 | # Android/IJ 52 | # 53 | react-native-dialogs.iml 54 | .idea 55 | .gradle 56 | local.properties 57 | android/*.iml 58 | 59 | ~assets/ 60 | .vscode 61 | *.tgz 62 | -------------------------------------------------------------------------------- /.markdownlint.json: -------------------------------------------------------------------------------- 1 | { 2 | "default": true, 3 | "line-length": false, 4 | "no-duplicate-header": { "siblings_only": true }, 5 | "no-inline-html": false 6 | } 7 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # react-native-cross-geolocation Changes 2 | 3 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 4 | 5 | ## \[1.1.0] - 2018-03-27 6 | 7 | ### Added 8 | 9 | - Missing Dependency on 'com.android.support:appcompat-v7' 10 | - Markdownlint configuration. 11 | 12 | ### Changed 13 | 14 | - Using Build Tools v28.0.3 with compileSdkVersion and targetSdkVersion 28 15 | - Using Gradle plugin 3.2.1 16 | - Using Java 1.8 17 | 18 | ### Removed 19 | 20 | - Dependency on 'com.android.support:support-annotations'. This must fix conflict issues with versions. 21 | 22 | ## \[1.0.6] - 2018-10-10 23 | 24 | ### Fixed 25 | 26 | - Error in getExtValue of build.gradle 27 | 28 | ## \[1.0.5] - 2018-10-09 29 | 30 | ### Fixed 31 | 32 | - Error in build.gradle no getting the correct `googlePlayServicesVersion` variable. 33 | - Minor fixes to the README. 34 | 35 | ## \[1.0.4] - 2018-09-09 36 | 37 | ### Changed 38 | 39 | - Minimum Android SDK version from 21 to 16. 40 | - Update README with a more clear note about the use of Gradle 4.4 41 | 42 | ### Fixed 43 | 44 | - #2 : Error in build.gradle. Thanks to @mowbell for reporting this. 45 | 46 | ## \[1.0.3] - 2018-06-23 47 | 48 | ### Added 49 | 50 | - Flow typings. 51 | 52 | ### Changed 53 | 54 | - Updated README. 55 | - The changelog follows the format on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). 56 | 57 | ### Fixed 58 | 59 | - PR #1 Fixes `undefined` error by the use of Geolocation instead RNGeolocation. Thanks to @badrange 60 | 61 | ## \[1.0.2] - 2018-06-18 62 | 63 | ### Fixed 64 | 65 | - `PositionError` builder 66 | 67 | ## \[1.0.1] - 2018-06-18 68 | 69 | ### Fixed 70 | 71 | - Typings for `setRNConfiguration` 72 | 73 | ## [1.0.0] - 2018-06-18 74 | 75 | - First public release 76 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Alberto Martínez 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-native-cross-geolocation 2 | 3 | [![npm][npm-image]](https://www.npmjs.com/package/react-native-cross-geolocation) 4 | [![License][license-image]](LICENSE) 5 | 6 | React Native Geolocation complatible module that uses the new [Google Play services location API](https://developer.android.com/training/location/) on Android devices. 7 | 8 | In my country (México), software developers are poorly paid, so I have had to look for another job to earn a living and I cannot dedicate more time to maintaining this and other repositories that over the years have never generated any money for me. If anyone is interested in maintaining this repository, I'd be happy to transfer it to them, along with the associated npm package. | 9 | :---: | 10 | En mi país (México), los desarrolladores de software somos pésimamente pagados, por lo que he tenido que buscar otro trabajo para ganarme la vida y no puedo dedicar más tiempo a mantener éste y otros repositorios que a través de los años nunca me generaron dinero. Si a alguien le interesa dar mantenimiento a este repositorio, con gusto se lo transferiré, así como el paquete de npm asociado. | 11 | 12 | If this library has helped you, please support my work with a star or [buy me a coffee][kofi-url]. 13 | 14 | ## IMPORTANT 15 | 16 | This module was tested with React Native 0.59.0, but it should work smoothly with apps that use Gradle 4.6 or later. 17 | 18 | \* For previous Gradle versions use react-native-cross-geolocation v1.0.6 or bellow. 19 | 20 | ## Setup 21 | 22 | ```bash 23 | yarn add react-native-cross-geolocation 24 | react-native link react-native-cross-geolocation 25 | ``` 26 | 27 | ### Play Services Location Version 28 | 29 | From v1.1.0, react-native-cross-geolocation supports the global variable `playServicesLocationVersion` to specify the version of 'com.google.android.gms:play-services-location' to use. It defaults to 16.0.0 30 | 31 | ### Configuration and Permissions 32 | 33 | This section only applies to projects made with `react-native init` or to those made with Create React Native App which have since ejected. For more information about ejecting, please see the [guide](https://github.com/react-community/create-react-native-app/blob/master/EJECTING.md) on the Create React Native App repository. 34 | 35 | #### iOS 36 | 37 | You need to include the NSLocationWhenInUseUsageDescription key in Info.plist to enable geolocation when using the app. Geolocation is enabled by default when you create a project with react-native init. 38 | 39 | In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info.plist and add location as a background mode in the 'Capabilities' tab in Xcode. 40 | 41 | #### Android 42 | 43 | To request access to location, add the following line to your app's AndroidManifest.xml: 44 | 45 | ```xml 46 | 47 | 48 | ``` 49 | 50 | Android API >= 18 Positions will also contain a `mocked` boolean to indicate if position was created from a mock provider. 51 | Android API >= 23 Permissions are handled automatically. 52 | 53 | #### Methods 54 | 55 | - [`setRNConfiguration`](#setrnconfiguration) 56 | - [`requestAuthorization`](#requestauthorization) 57 | - [`getCurrentPosition`](#getcurrentposition) 58 | - [`watchPosition`](#watchposition) 59 | - [`clearWatch`](#clearwatch) 60 | - [`stopObserving`](#stopobserving) 61 | 62 | ## Reference 63 | 64 | ### Methods 65 | 66 | #### `setRNConfiguration()` 67 | 68 | ```js 69 | Geolocation.setRNConfiguration(config); 70 | ``` 71 | 72 | Sets configuration options that will be used in all location requests. 73 | 74 | Parameters: 75 | 76 | NAME | TYPE | REQUIRED | DESCRIPTION 77 | ---- | ---- | -------- | ----------- 78 | config | object | Yes | See below. 79 | 80 | Supported options: 81 | 82 | - `skipPermissionRequests` (boolean, iOS-only) - Defaults to `false`. If `true`, you must request permissions before using Geolocation APIs. 83 | - `lowAccuracyMode` (number, Android-only) - Defaults to [LowAccuracyMode.BALANCED](#constants). 84 | - `fastestInterval` (number, Android-only) - Defaults to 10000 (10 secs). 85 | - `updateInterval` (number, Android-only) - Defaults to 5000 (5 secs). 86 | 87 | #### `requestAuthorization()` 88 | 89 | ```js 90 | Geolocation.requestAuthorization(); 91 | ``` 92 | 93 | Request suitable Location permission based on the key configured on pList. If NSLocationAlwaysUsageDescription is set, it will request Always authorization, although if NSLocationWhenInUseUsageDescription is set, it will request InUse authorization. 94 | 95 | #### `getCurrentPosition()` 96 | 97 | ```js 98 | Geolocation.getCurrentPosition(geo_success, [geo_error], [geo_options]); 99 | ``` 100 | 101 | Invokes the success callback once with the latest location info. 102 | 103 | Parameters: 104 | 105 | NAME | TYPE | REQUIRED | DESCRIPTION 106 | ---- | ---- | -------- | ----------- 107 | geo_success | function | Yes | Invoked with latest location info. 108 | geo_error | function | No | Invoked whenever an error is encountered. 109 | geo_options | object | No | See below. 110 | 111 | Supported options: 112 | 113 | - `timeout` (ms) - Defaults to MAX_VALUE 114 | - `maximumAge` (ms) - Defaults to INFINITY. 115 | - `enableHighAccuracy` (bool) - On Android, if the location is cached this can return almost immediately, or it will request an update which might take a while. 116 | 117 | #### `watchPosition()` 118 | 119 | ```js 120 | Geolocation.watchPosition(success, [error], [options]); 121 | ``` 122 | 123 | Invokes the success callback whenever the location changes. Returns a `watchId` (number). 124 | 125 | Parameters: 126 | 127 | NAME | TYPE | REQUIRED | DESCRIPTION 128 | ---- | ---- | -------- | ----------- 129 | success | function | Yes | Invoked whenever the location changes. 130 | error | function | No | Invoked whenever an error is encountered. 131 | options | object | No | See below. 132 | 133 | Supported options: 134 | 135 | - `timeout` (ms) - Defaults to MAX_VALUE. 136 | - `maximumAge` (ms) - Defaults to INFINITY. 137 | - `enableHighAccuracy` (bool) - Defaults to `false`. 138 | - `distanceFilter` (m) - Defaults to 100. 139 | - `useSignificantChanges` (bool) (unused in Android). 140 | 141 | #### `clearWatch()` 142 | 143 | ```js 144 | Geolocation.clearWatch(watchID); 145 | ``` 146 | 147 | Parameters: 148 | 149 | NAME | TYPE | REQUIRED | DESCRIPTION 150 | ---- | ---- | -------- | ----------- 151 | watchID | number | Yes | Id as returned by `watchPosition()`. 152 | 153 | #### `stopObserving()` 154 | 155 | ```js 156 | Geolocation.stopObserving(); 157 | ``` 158 | 159 | Stops observing for device location changes. In addition, it removes all listeners previously registered. 160 | 161 | Notice that this method has only effect if the `geolocation.watchPosition(successCallback, errorCallback)` method was previously invoked. 162 | 163 | ### Constants 164 | 165 | rnCrossGeolocation exports a `LowAccuracyMode` object with values to be used in the `lowAccuracyMode` property of the parameter sent to [`setRNConfiguration`](#setrnconfiguration): 166 | 167 | NAME | DETAILS 168 | ---- | ------- 169 | LowAccuracyMode.BALANCED
(102)
This is the default mode. | Request location precision to within a city block, which is an accuracy of approximately 100 meters.
This is considered a coarse level of accuracy, and is likely to consume less power. With this setting, the location services are likely to use WiFi and cell tower positioning. Note, however, that the choice of location provider depends on many other factors, such as which sources are available. 170 | LowAccuracyMode.LOW_POWER
(104) | Request city-level precision, which is an accuracy of approximately 10 Km.
This is considered a coarse level of accuracy, and is likely to consume less power. 171 | LowAccuracyMode.NO_POWER
(105) | Use this if you need negligible impact on power consumption, but want to receive location updates when available.
With this setting, your app does not trigger any location updates, but receives locations triggered by other apps. 172 | 173 | _**NOTE:** These constants are only for Android, on iOS they are undefined._ 174 | 175 | ## TODO 176 | 177 | - [ ] Tests 178 | 179 | ## Support my Work 180 | 181 | I'm a full-stack developer with more than 20 year of experience and I try to share most of my work for free and help others, but this takes a significant amount of time and effort so, if you like my work, please consider... 182 | 183 | [][kofi-url] 184 | 185 | Of course, feedback, PRs, and stars are also welcome 🙃 186 | 187 | Thanks for your support! 188 | 189 | [npm-image]: https://img.shields.io/npm/v/react-native-cross-geolocation.svg 190 | [license-image]: https://img.shields.io/npm/l/express.svg 191 | [kofi-url]: https://ko-fi.com/C0C7LF7I 192 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | def safeExtGet(prop, fallback) { 2 | rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback 3 | } 4 | 5 | // Google Play Services 12.0.x to 15.0.x depends on support libraries 26.1.0 6 | def _playServicesLocationVersion = safeExtGet('playServicesLocation', '16.0.0') 7 | def _buildToolsVersion = safeExtGet('buildToolsVersion', '28.0.3') 8 | def _compileSdkVersion = safeExtGet('compileSdkVersion', 28) 9 | def _targetSdkVersion = safeExtGet('targetSdkVersion', 28) 10 | def _minSdkVersion = safeExtGet('minSdkVersion', 16) 11 | def _supportLibVersion = safeExtGet('supportLibVersion', '28.0.0') 12 | 13 | buildscript { 14 | repositories { 15 | google() 16 | jcenter() 17 | } 18 | dependencies { 19 | classpath 'com.android.tools.build:gradle:3.2.1' 20 | } 21 | } 22 | 23 | apply plugin: 'com.android.library' 24 | 25 | android { 26 | compileSdkVersion _compileSdkVersion 27 | buildToolsVersion _buildToolsVersion 28 | 29 | defaultConfig { 30 | minSdkVersion _minSdkVersion 31 | targetSdkVersion _targetSdkVersion 32 | versionCode 2 33 | versionName '1.1.0' 34 | } 35 | lintOptions { 36 | abortOnError false 37 | } 38 | compileOptions { 39 | sourceCompatibility JavaVersion.VERSION_1_8 40 | targetCompatibility JavaVersion.VERSION_1_8 41 | } 42 | } 43 | 44 | repositories { 45 | mavenLocal() 46 | google() 47 | jcenter() 48 | maven { url "$rootDir/../node_modules/react-native/android" } 49 | } 50 | 51 | dependencies { 52 | compileOnly 'com.facebook.react:react-native:+' 53 | implementation "com.google.android.gms:play-services-location:${_playServicesLocationVersion}" 54 | implementation "com.android.support:appcompat-v7:${_supportLibVersion}" 55 | } 56 | 57 | task customClean(type: Delete) { 58 | delete rootProject.buildDir 59 | } 60 | 61 | clean.dependsOn customClean 62 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aMarCruz/react-native-cross-geolocation/5794266ec9cf2d93bef465b3f107bbfda2b217fa/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Sep 09 08:55:54 CDT 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip 7 | -------------------------------------------------------------------------------- /android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /android/src/main/java/com/github/amarcruz/geolocation/Constants.java: -------------------------------------------------------------------------------- 1 | package com.github.amarcruz.geolocation; 2 | 3 | final class Constants { 4 | private Constants() {} 5 | 6 | static final String TAG = "RNGeolocation"; 7 | static final int PLAY_SERVICES_REQUEST = 11404; 8 | } 9 | -------------------------------------------------------------------------------- /android/src/main/java/com/github/amarcruz/geolocation/LocationOptions.java: -------------------------------------------------------------------------------- 1 | package com.github.amarcruz.geolocation; 2 | 3 | import com.facebook.react.bridge.ReadableMap; 4 | import com.google.android.gms.location.LocationRequest; 5 | 6 | final class LocationOptions { 7 | private static final float DEFAULT_DISTANCE_FILTER = 100f; 8 | 9 | private static long fastestInterval = 5000; // 5 secs 10 | private static long updateInterval = 10000; // 10 secs 11 | private static int lowPriorityMode = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY; 12 | 13 | final long timeout; 14 | final double maximumAge; 15 | final float distanceFilter; 16 | final int priority; 17 | 18 | private LocationOptions( 19 | final long timeout, 20 | final double maximumAge, 21 | final boolean highAccuracy, 22 | final float distanceFilter 23 | ) { 24 | this.timeout = timeout; 25 | this.maximumAge = maximumAge; 26 | this.distanceFilter = distanceFilter; 27 | this.priority = highAccuracy ? LocationRequest.PRIORITY_HIGH_ACCURACY : lowPriorityMode; 28 | } 29 | 30 | static LocationOptions fromReactMap(final ReadableMap map) { 31 | long timeout = Long.MAX_VALUE; 32 | double maximumAge = Double.POSITIVE_INFINITY; 33 | boolean highAccuracy = false; 34 | float distanceFilter = DEFAULT_DISTANCE_FILTER; 35 | 36 | if (map != null) { 37 | // precision might be dropped on timeout (double -> int conversion), but that's OK 38 | if (map.hasKey("timeout")) { 39 | timeout = (long) map.getDouble("timeout"); 40 | } 41 | if (map.hasKey("maximumAge")) { 42 | maximumAge = map.getDouble("maximumAge"); 43 | } 44 | if (map.hasKey("enableHighAccuracy")) { 45 | highAccuracy = map.getBoolean("enableHighAccuracy"); 46 | } 47 | if (map.hasKey("distanceFilter")) { 48 | distanceFilter = (float) map.getDouble("distanceFilter"); 49 | } 50 | } 51 | 52 | return new LocationOptions(timeout, maximumAge, highAccuracy, distanceFilter); 53 | } 54 | 55 | static void setConfiguration (final ReadableMap map) { 56 | if (map != null) { 57 | if (map.hasKey("fastestInterval")) { 58 | fastestInterval = (long) map.getDouble("fastestInterval"); 59 | } 60 | if (map.hasKey("updateInterval")) { 61 | updateInterval = (long) map.getDouble("updateInterval"); 62 | } 63 | if (map.hasKey("lowPriorityMode")) { 64 | int mode = map.getInt("lowPriorityMode"); 65 | if (mode != LocationRequest.PRIORITY_LOW_POWER && mode != LocationRequest.PRIORITY_NO_POWER) { 66 | mode = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY; 67 | } 68 | lowPriorityMode = mode; 69 | } 70 | } 71 | } 72 | 73 | static long getFastestInterval () { 74 | return fastestInterval; 75 | } 76 | 77 | static long getUpdateInterval () { 78 | return updateInterval; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /android/src/main/java/com/github/amarcruz/geolocation/LocationResolver.java: -------------------------------------------------------------------------------- 1 | package com.github.amarcruz.geolocation; 2 | 3 | import android.location.Location; 4 | import android.util.Log; 5 | 6 | import com.facebook.react.bridge.Arguments; 7 | import com.facebook.react.bridge.Callback; 8 | import com.facebook.react.bridge.WritableMap; 9 | 10 | class LocationResolver { 11 | static private final String TAG = Constants.TAG; 12 | 13 | private Callback mSuccessCallback; 14 | private Callback mErrorCallback; 15 | private boolean done = false; 16 | 17 | LocationResolver(final Callback success, final Callback error) { 18 | mSuccessCallback = success; 19 | mErrorCallback = error; 20 | } 21 | 22 | void success(final Location place) { 23 | if (mSuccessCallback != null && !done) { 24 | done = true; 25 | try { 26 | if (place != null) { 27 | mSuccessCallback.invoke(locationToMap(place)); 28 | } else { 29 | mErrorCallback.invoke( 30 | PositionError.buildError(PositionError.POSITION_UNAVAILABLE, "Canceled.")); 31 | } 32 | } catch (Exception ex) { 33 | mErrorCallback.invoke( 34 | PositionError.buildError(PositionError.POSITION_UNAVAILABLE, ex.getMessage())); 35 | } finally { 36 | mSuccessCallback = null; 37 | mErrorCallback = null; 38 | } 39 | } 40 | } 41 | 42 | void error(final int code, final String message) { 43 | if (mErrorCallback != null && !done) { 44 | done = true; 45 | Log.e(TAG, "Location error: " + message); 46 | mErrorCallback.invoke(PositionError.buildError(code, message)); 47 | mErrorCallback = null; 48 | } 49 | } 50 | 51 | void error(final String message) { 52 | error(PositionError.POSITION_UNAVAILABLE, message); 53 | } 54 | 55 | static WritableMap locationToMap(Location location) { 56 | WritableMap map = Arguments.createMap(); 57 | WritableMap coords = Arguments.createMap(); 58 | 59 | coords.putDouble("latitude", location.getLatitude()); 60 | coords.putDouble("longitude", location.getLongitude()); 61 | coords.putDouble("altitude", location.getAltitude()); 62 | coords.putDouble("accuracy", location.getAccuracy()); 63 | coords.putDouble("heading", location.getBearing()); 64 | coords.putDouble("speed", location.getSpeed()); 65 | map.putMap("coords", coords); 66 | map.putDouble("timestamp", location.getTime()); 67 | if (android.os.Build.VERSION.SDK_INT >= 18) { 68 | map.putBoolean("mocked", location.isFromMockProvider()); 69 | } 70 | 71 | return map; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /android/src/main/java/com/github/amarcruz/geolocation/PositionError.java: -------------------------------------------------------------------------------- 1 | package com.github.amarcruz.geolocation; 2 | 3 | import com.facebook.react.bridge.Arguments; 4 | import com.facebook.react.bridge.WritableMap; 5 | 6 | /** 7 | * @see PositionError 8 | */ 9 | final class PositionError { 10 | /** 11 | * The acquisition of the geolocation information failed because 12 | * the page didn't have the permission to do it. 13 | */ 14 | static int PERMISSION_DENIED = 1; 15 | 16 | /** 17 | * The acquisition of the geolocation failed because at least one 18 | * internal source of position returned an internal error. 19 | */ 20 | static int POSITION_UNAVAILABLE = 2; 21 | 22 | static WritableMap buildError(final int code, final String message) { 23 | WritableMap error = Arguments.createMap(); 24 | error.putInt("code", code); 25 | if (message != null) { 26 | error.putString("message", message); 27 | } 28 | return error; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /android/src/main/java/com/github/amarcruz/geolocation/RNGeolocationModule.java: -------------------------------------------------------------------------------- 1 | package com.github.amarcruz.geolocation; 2 | 3 | import android.Manifest; 4 | import android.app.Activity; 5 | import android.content.pm.PackageManager; 6 | import android.location.Location; 7 | import android.support.v4.app.ActivityCompat; 8 | import android.util.Log; 9 | 10 | import com.facebook.react.bridge.Callback; 11 | import com.facebook.react.bridge.ReactApplicationContext; 12 | import com.facebook.react.bridge.ReactContextBaseJavaModule; 13 | import com.facebook.react.bridge.ReactMethod; 14 | import com.facebook.react.bridge.ReadableMap; 15 | import com.facebook.react.bridge.WritableMap; 16 | import com.facebook.react.common.SystemClock; 17 | 18 | import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter; 19 | import com.google.android.gms.common.ConnectionResult; 20 | import com.google.android.gms.common.GoogleApiAvailability; 21 | import com.google.android.gms.common.api.ApiException; 22 | import com.google.android.gms.location.FusedLocationProviderClient; 23 | import com.google.android.gms.location.LocationCallback; 24 | import com.google.android.gms.location.LocationRequest; 25 | import com.google.android.gms.location.LocationResult; 26 | import com.google.android.gms.location.LocationServices; 27 | import com.google.android.gms.location.LocationSettingsRequest; 28 | import com.google.android.gms.location.SettingsClient; 29 | 30 | import java.util.HashMap; 31 | import java.util.Map; 32 | 33 | public class RNGeolocationModule extends ReactContextBaseJavaModule { 34 | private static final String TAG = Constants.TAG; 35 | 36 | private FusedLocationProviderClient mFusedProviderClient; 37 | private boolean mRequestingLocationUpdates = false; 38 | 39 | private final LocationCallback mLocationCallback = new LocationCallback() { 40 | @Override 41 | public void onLocationResult(LocationResult locationResult) { 42 | synchronized (RNGeolocationModule.this) { 43 | if (locationResult != null) { 44 | emitSuccess(locationResult.getLastLocation()); 45 | } 46 | } 47 | } 48 | }; 49 | 50 | RNGeolocationModule(ReactApplicationContext reactContext) { 51 | super(reactContext); 52 | mFusedProviderClient = LocationServices.getFusedLocationProviderClient(reactContext); 53 | } 54 | 55 | @Override 56 | public String getName() { 57 | return TAG; 58 | } 59 | 60 | @Override 61 | public Map getConstants() { 62 | final Map constants = new HashMap<>(); 63 | 64 | constants.put("HIGH_ACCURACY", LocationRequest.PRIORITY_HIGH_ACCURACY); 65 | constants.put("BALANCED", LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 66 | constants.put("LOW_POWER", LocationRequest.PRIORITY_LOW_POWER); 67 | constants.put("NO_POWER", LocationRequest.PRIORITY_NO_POWER); 68 | 69 | return constants; 70 | } 71 | 72 | @ReactMethod 73 | public void setConfiguration(final ReadableMap conf) { 74 | LocationOptions.setConfiguration(conf); 75 | } 76 | 77 | @ReactMethod 78 | public void getCurrentPosition(ReadableMap options, final Callback success, final Callback error) { 79 | final ReactApplicationContext context = getReactApplicationContext(); 80 | final Activity activity = context.getCurrentActivity(); 81 | final LocationOptions opts = LocationOptions.fromReactMap(options); 82 | final LocationResolver resolver = new LocationResolver(success, error); 83 | 84 | if (activity == null) { 85 | resolver.error("Cannot get activity."); 86 | return; 87 | } 88 | 89 | if (isPlayServicesNotAvailable(context)) { 90 | resolver.error("Google Play Service not available."); 91 | return; 92 | } 93 | 94 | if (!hasPermissions(context)) { 95 | resolver.error(PositionError.PERMISSION_DENIED, "Location permission not granted."); 96 | return; 97 | } 98 | 99 | final SettingsClient settingsClient = LocationServices.getSettingsClient(context); 100 | 101 | final LocationRequest locationRequest = new LocationRequest() 102 | .setInterval(LocationOptions.getUpdateInterval()) 103 | .setFastestInterval(LocationOptions.getFastestInterval()) 104 | .setPriority(opts.priority) 105 | .setExpirationDuration(opts.timeout); 106 | 107 | final LocationSettingsRequest locationSettingsRequest = new LocationSettingsRequest.Builder() 108 | .addLocationRequest(locationRequest) 109 | .build(); 110 | 111 | settingsClient.checkLocationSettings(locationSettingsRequest) 112 | .addOnSuccessListener(activity, task -> { 113 | // All location settings are satisfied. 114 | getUserLocation(locationRequest, opts, resolver); 115 | }) 116 | .addOnFailureListener(activity, ex -> { 117 | final int code = ((ApiException) ex).getStatusCode(); 118 | resolver.error("Error " + code + ": " + ex.getMessage()); 119 | }); 120 | } 121 | 122 | @ReactMethod 123 | public void stopObserving() { 124 | if (mRequestingLocationUpdates) { 125 | mRequestingLocationUpdates = false; 126 | try { 127 | mFusedProviderClient.removeLocationUpdates(mLocationCallback); 128 | } catch (Exception ex) { 129 | ex.printStackTrace(); 130 | } 131 | } 132 | } 133 | 134 | @ReactMethod 135 | public void startObserving(final ReadableMap opts) { 136 | if (mRequestingLocationUpdates) { 137 | return; 138 | } 139 | mRequestingLocationUpdates = true; 140 | mRequestingLocationUpdates = startUpdater(LocationOptions.fromReactMap(opts)); 141 | } 142 | 143 | private void getUserLocation( 144 | final LocationRequest locationRequest, 145 | final LocationOptions options, 146 | final LocationResolver resolver 147 | ) { 148 | final ReactApplicationContext context = getReactApplicationContext(); 149 | 150 | if (mFusedProviderClient != null && hasPermissions(context)) { 151 | try { 152 | mFusedProviderClient.getLastLocation().addOnCompleteListener(task -> { 153 | Location location = task.getResult(); 154 | 155 | if (location != null && 156 | (SystemClock.currentTimeMillis() - location.getTime()) < options.maximumAge) { 157 | resolver.success(location); 158 | } else { 159 | // Last location not available, request new location. 160 | new SingleLocationRequest( 161 | mFusedProviderClient, 162 | locationRequest, 163 | resolver).getLocation(); 164 | } 165 | }); 166 | } catch (SecurityException ex) { 167 | emitError(PositionError.PERMISSION_DENIED, ex.getMessage()); 168 | } 169 | } 170 | } 171 | 172 | private boolean startUpdater (final LocationOptions options) { 173 | final ReactApplicationContext context = getReactApplicationContext(); 174 | final Activity activity = context.getCurrentActivity(); 175 | 176 | if (activity == null) { 177 | emitError("Cannot get activity."); 178 | return false; 179 | } 180 | 181 | if (isPlayServicesNotAvailable(context)) { 182 | emitError("Google Play Service not available."); 183 | return false; 184 | } 185 | 186 | if (!hasPermissions(context)) { 187 | emitError(PositionError.PERMISSION_DENIED, "Location permission not granted."); 188 | return false; 189 | } 190 | 191 | try { 192 | final SettingsClient settingsClient = LocationServices.getSettingsClient(context); 193 | 194 | final LocationRequest locationRequest = new LocationRequest() 195 | .setInterval(LocationOptions.getUpdateInterval()) 196 | .setFastestInterval(LocationOptions.getFastestInterval()) 197 | .setPriority(options.priority) 198 | .setExpirationDuration(options.timeout) 199 | .setSmallestDisplacement(options.distanceFilter); 200 | 201 | final LocationSettingsRequest locationSettingsRequest = new LocationSettingsRequest.Builder() 202 | .addLocationRequest(locationRequest) 203 | .build(); 204 | 205 | settingsClient.checkLocationSettings(locationSettingsRequest) 206 | .addOnSuccessListener(activity, task -> { 207 | // All location settings are satisfied. 208 | mFusedProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, null) 209 | .addOnFailureListener(e -> emitError(e.getMessage())); 210 | 211 | }) 212 | .addOnFailureListener(activity, ex -> { 213 | final int code = ((ApiException) ex).getStatusCode(); 214 | emitError("Error " + code + ": " + ex.getMessage()); 215 | }); 216 | return true; 217 | 218 | } catch (SecurityException ex) { 219 | emitError(PositionError.PERMISSION_DENIED, ex.getMessage()); 220 | return false; 221 | } 222 | } 223 | 224 | private void emitSuccess(final Location location) { 225 | final ReactApplicationContext reactContext = getReactApplicationContext(); 226 | 227 | if (reactContext.hasActiveCatalystInstance()) { 228 | final WritableMap result = LocationResolver.locationToMap(location); 229 | reactContext 230 | .getJSModule(RCTDeviceEventEmitter.class) 231 | .emit("geolocationDidChange", result); 232 | } else { 233 | Log.i(TAG, "Waiting for Catalyst Instance..."); 234 | } 235 | } 236 | 237 | private void emitError(int code, String message) { 238 | final ReactApplicationContext reactContext = getReactApplicationContext(); 239 | 240 | if (reactContext.hasActiveCatalystInstance()) { 241 | reactContext 242 | .getJSModule(RCTDeviceEventEmitter.class) 243 | .emit("geolocationError", PositionError.buildError(code, message)); 244 | } else { 245 | Log.i(TAG, "Waiting for Catalyst Instance..."); 246 | } 247 | } 248 | 249 | private void emitError(final String message) { 250 | emitError(PositionError.POSITION_UNAVAILABLE, message); 251 | } 252 | 253 | private static boolean hasPermissions(final ReactApplicationContext context) { 254 | return (ActivityCompat.checkSelfPermission( 255 | context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) || 256 | (ActivityCompat.checkSelfPermission( 257 | context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED); 258 | } 259 | 260 | private boolean isPlayServicesNotAvailable(final ReactApplicationContext context) { 261 | final GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance(); 262 | final int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(context); 263 | 264 | if (resultCode == ConnectionResult.SUCCESS) { 265 | return false; 266 | } 267 | 268 | if (googleApiAvailability.isUserResolvableError(resultCode)) { 269 | googleApiAvailability.getErrorDialog( 270 | getCurrentActivity(), resultCode, Constants.PLAY_SERVICES_REQUEST).show(); 271 | } 272 | return true; 273 | } 274 | } 275 | -------------------------------------------------------------------------------- /android/src/main/java/com/github/amarcruz/geolocation/RNGeolocationPackage.java: -------------------------------------------------------------------------------- 1 | package com.github.amarcruz.geolocation; 2 | 3 | import com.facebook.react.ReactPackage; 4 | import com.facebook.react.bridge.NativeModule; 5 | import com.facebook.react.bridge.ReactApplicationContext; 6 | import com.facebook.react.uimanager.ViewManager; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Collections; 10 | import java.util.List; 11 | 12 | @SuppressWarnings("unused") 13 | public class RNGeolocationPackage implements ReactPackage { 14 | 15 | public RNGeolocationPackage() { 16 | } 17 | 18 | @Override 19 | public List createViewManagers(ReactApplicationContext reactContext) { 20 | return Collections.emptyList(); 21 | } 22 | 23 | @Override 24 | public List createNativeModules(ReactApplicationContext reactContext) { 25 | List modules = new ArrayList<>(); 26 | modules.add(new RNGeolocationModule(reactContext)); 27 | return modules; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /android/src/main/java/com/github/amarcruz/geolocation/SingleLocationRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.amarcruz.geolocation; 2 | 3 | import android.os.Looper; 4 | 5 | import com.google.android.gms.common.api.ApiException; 6 | import com.google.android.gms.location.FusedLocationProviderClient; 7 | import com.google.android.gms.location.LocationCallback; 8 | import com.google.android.gms.location.LocationRequest; 9 | import com.google.android.gms.location.LocationResult; 10 | 11 | class SingleLocationRequest { 12 | private final FusedLocationProviderClient mFusedProviderClient; 13 | private final LocationRequest mLocationRequest; 14 | private final LocationResolver mResolver; 15 | 16 | private LocationCallback mLocationCallback = new LocationCallback() { 17 | @Override 18 | public void onLocationResult(LocationResult locationResult) { 19 | synchronized (SingleLocationRequest.this) { 20 | if (locationResult != null) { 21 | removeCallback(); 22 | mResolver.success(locationResult.getLastLocation()); 23 | } 24 | } 25 | } 26 | }; 27 | 28 | private void removeCallback () { 29 | final LocationCallback callback = mLocationCallback; 30 | mLocationCallback = null; 31 | if (callback != null) { 32 | try { 33 | mFusedProviderClient.removeLocationUpdates(callback); 34 | } catch (Exception ex) { 35 | ex.printStackTrace(); 36 | } 37 | } 38 | } 39 | 40 | SingleLocationRequest( 41 | final FusedLocationProviderClient fusedProviderClient, 42 | final LocationRequest locationRequest, 43 | final LocationResolver resolver) { 44 | mFusedProviderClient = fusedProviderClient; 45 | mLocationRequest = locationRequest; 46 | mResolver = resolver; 47 | } 48 | 49 | /** 50 | * Request one time location update 51 | */ 52 | void getLocation () { 53 | if (mFusedProviderClient == null) { 54 | mResolver.error(PositionError.POSITION_UNAVAILABLE, "No location provider available."); 55 | return; 56 | } 57 | 58 | try { 59 | mFusedProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper()) 60 | .addOnFailureListener(ex -> { 61 | removeCallback(); 62 | try { 63 | final int code = ((ApiException) ex).getStatusCode(); 64 | mResolver.error("Error " + code + ": " + ex.getMessage()); 65 | } catch (Exception ignore) { 66 | mResolver.error(ex.getMessage()); 67 | } 68 | }); 69 | } catch (SecurityException ex) { 70 | mResolver.error(PositionError.PERMISSION_DENIED, ex.getMessage()); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /geoloc.js: -------------------------------------------------------------------------------- 1 | import { 2 | NativeEventEmitter, 3 | NativeModules, 4 | PermissionsAndroid, 5 | Platform, 6 | } from 'react-native' 7 | import invariant from 'invariant' 8 | //const logError = require('logError'); 9 | //const warning = require('fbjs/lib/warning'); 10 | 11 | const RNGeolocation = NativeModules.LocationObserver 12 | const LocationEventEmitter = new NativeEventEmitter(RNGeolocation) 13 | const logError = () => {} 14 | 15 | var nextWatchID = 1 16 | var subscriptions = {} 17 | var updatesEnabled = false 18 | 19 | /** 20 | * The Geolocation API extends the web spec: 21 | * https://developer.mozilla.org/en-US/docs/Web/API/Geolocation 22 | * 23 | * See https://facebook.github.io/react-native/docs/geolocation.html 24 | */ 25 | module.exports = { 26 | 27 | LowAccuracyMode: { 28 | BALANCED: RNGeolocation.BALANCED, 29 | LOW_POWER: RNGeolocation.LOW_POWER, 30 | NO_POWER: RNGeolocation.NO_POWER, 31 | }, 32 | 33 | /* 34 | * Sets configuration options that will be used in all location requests. 35 | * 36 | * See https://facebook.github.io/react-native/docs/geolocation.html#setrnconfiguration 37 | * 38 | */ 39 | setRNConfiguration: RNGeolocation.setConfiguration, 40 | 41 | /* 42 | * Request suitable Location permission based on the key configured on pList. 43 | * 44 | * See https://facebook.github.io/react-native/docs/geolocation.html#requestauthorization 45 | */ 46 | requestAuthorization () {}, 47 | 48 | /* 49 | * Invokes the success callback once with the latest location info. 50 | * 51 | * See https://facebook.github.io/react-native/docs/geolocation.html#getcurrentposition 52 | */ 53 | getCurrentPosition(geo_success, geo_error, geo_options) { 54 | invariant( 55 | typeof geo_success === 'function', 56 | 'Must provide a valid geo_success callback.' 57 | ) 58 | let promise 59 | 60 | // Supports Android's new permission model. For Android older devices, 61 | // it's always on. 62 | if (Platform.Version >= 23) { 63 | promise = PermissionsAndroid.check( 64 | PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION 65 | ).then((hasPermission) => { 66 | if (hasPermission) { 67 | return true 68 | } 69 | return PermissionsAndroid.request( 70 | PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION 71 | ) 72 | }) 73 | } else { 74 | promise = Promise.resolve() 75 | } 76 | 77 | promise.then(() => { 78 | // native module will call geo_error if has no parmissions 79 | RNGeolocation.getCurrentPosition( 80 | geo_options || {}, 81 | geo_success, 82 | geo_error || logError 83 | ) 84 | }) 85 | }, 86 | 87 | /* 88 | * Invokes the success callback whenever the location changes. 89 | * 90 | * See https://facebook.github.io/react-native/docs/geolocation.html#watchposition 91 | */ 92 | watchPosition (success, error, options) { 93 | if (!updatesEnabled) { 94 | RNGeolocation.startObserving(options || {}) 95 | updatesEnabled = true 96 | } 97 | const watchID = String(nextWatchID++) 98 | subscriptions[watchID] = [ 99 | LocationEventEmitter.addListener( 100 | 'geolocationDidChange', 101 | success 102 | ), 103 | error ? LocationEventEmitter.addListener( 104 | 'geolocationError', 105 | error 106 | ) : null, 107 | ] 108 | return watchID 109 | }, 110 | 111 | clearWatch (watchID) { 112 | var sub = subscriptions[watchID] 113 | if (!sub) { 114 | // Silently exit when the watchID is invalid or already cleared 115 | // This is consistent with timers 116 | return 117 | } 118 | 119 | sub[0].remove() 120 | // array element refinements not yet enabled in Flow 121 | if (sub[1]) { 122 | sub[1].remove() 123 | } 124 | delete subscriptions[watchID] 125 | for (var p in subscriptions) { 126 | if (subscriptions.hasOwnProperty(p)) { 127 | return // still valid subscriptions 128 | } 129 | } 130 | RNGeolocation.stopObserving() 131 | }, 132 | 133 | stopObserving () { 134 | if (updatesEnabled) { 135 | RNGeolocation.stopObserving() 136 | updatesEnabled = false 137 | Object.keys(subscriptions).forEach((id) => { 138 | const sub = subscriptions[id] 139 | if (sub) { 140 | //warning(false, 'Called stopObserving with existing subscriptions.'); 141 | sub[0].remove() 142 | if (sub[1]) { 143 | sub[1].remove() 144 | } 145 | } 146 | }) 147 | subscriptions = {} 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | declare module "react-native-cross-geolocation" { 2 | 3 | export type GeolocationReturnType = { 4 | coords: { 5 | latitude: number, 6 | longitude: number, 7 | altitude: number | null, 8 | accuracy: number, 9 | altitudeAccuracy: number | null, 10 | heading: number | null, 11 | speed: number | null, 12 | }; 13 | timestamp: number, 14 | mocked?: boolean, 15 | }; 16 | 17 | export type GeolocationError = { 18 | code: number, 19 | message: string, 20 | PERMISSION_DENIED: number, 21 | POSITION_UNAVAILABLE: number, 22 | TIMEOUT: number, 23 | }; 24 | 25 | export type SuccessCb = (loc: GeolocationReturnType) => void 26 | export type ErrorCb = (err: GeolocationError) => void 27 | 28 | export type LowAccuracyMode = { 29 | /** 30 | * Use this setting to request location precision to within a city block, which 31 | * is an accuracy of approximately 100 meters. 32 | * This is considered a coarse level of accuracy, and is likely to consume less power. 33 | * With this setting, the location services are likely to use WiFi and cell tower 34 | * positioning. Note, however, that the choice of location provider depends on many 35 | * other factors, such as which sources are available. 36 | */ 37 | readonly BALANCED: number, 38 | /** 39 | * Use this setting to request city-level precision, which is an accuracy of 40 | * approximately 10 kilometers. This is considered a coarse level of accuracy, 41 | * and is likely to consume less power. 42 | */ 43 | readonly LOW_POWER: number, 44 | /** 45 | * Use this setting if you need negligible impact on power consumption, but want 46 | * to receive location updates when available. With this setting, your app does 47 | * not trigger any location updates, but receives locations triggered by other apps. 48 | */ 49 | readonly NO_POWER: number, 50 | } 51 | 52 | export type GeolocConfigAndroid = { 53 | /** 54 | * One of Geolocation.LowAccuracyMode 55 | * @default LowAccuracyMode.BALANCED 56 | */ 57 | lowAccuracyMode?: number, 58 | /** 59 | * milliseconds 60 | * @default 10000 61 | */ 62 | fastestInterval?: number, 63 | /** 64 | * milliseconds 65 | * @default 5000 66 | */ 67 | updateInterval?: number, 68 | } 69 | 70 | export type GeolocConfigIOS = { 71 | skipPermissionRequests: boolean; 72 | } 73 | 74 | export type GeolocOptions = { 75 | /** 76 | * Milliseconds. 77 | * @default MAX_VALUE 78 | */ 79 | timeout?: number, 80 | /** 81 | * Milliseconds. 82 | * @default INFINITY 83 | */ 84 | maximumAge?: number, 85 | /** 86 | * Use this setting to request the most precise location possible. 87 | * With this setting, the location services are more likely to use GPS to determine 88 | * the location. 89 | * 90 | * On Android, if the location is cached this can return almost immediately, or it 91 | * will request an update which might take a while. 92 | * 93 | * @default false 94 | */ 95 | enableHighAccuracy?: boolean, 96 | } 97 | 98 | export interface GeolocWatcherOptions extends GeolocOptions { 99 | /** 100 | * Meters 101 | * @default 100.0 102 | */ 103 | distanceFilter?: number, 104 | /** 105 | * 106 | */ 107 | useSignificantChanges?: boolean, 108 | } 109 | 110 | interface GeolocStatic { 111 | /** 112 | * Sets configuration options that will be used in all location requests. 113 | */ 114 | setRNConfiguration(config: GeolocConfigAndroid | GeolocConfigIOS): void; 115 | /** 116 | * Request suitable Location permission based on the key configured on pList. If 117 | * NSLocationAlwaysUsageDescription is set, it will request Always authorization, although if 118 | * NSLocationWhenInUseUsageDescription is set, it will request InUse authorization. 119 | */ 120 | requestAuthorization(): void; 121 | /** 122 | * Invokes the success callback once with the latest location info. 123 | */ 124 | getCurrentPosition(success: SuccessCb, error?: ErrorCb, options?: GeolocOptions): void; 125 | /** 126 | * Invokes the success callback whenever the location changes. Returns a watchId (number). 127 | */ 128 | watchPosition(success: SuccessCb, error?: ErrorCb, options?: GeolocWatcherOptions): number; 129 | /** 130 | * Clear a watcher. 131 | * @param watchID The ID received from `watchPosition` 132 | */ 133 | clearWatch(watchID: number): void; 134 | /** 135 | * Stops observing for device location changes. In addition, it removes all listeners 136 | * previously registered. 137 | */ 138 | stopObserving(): void; 139 | } 140 | 141 | const Geolocation: GeolocStatic; 142 | export default Geolocation; 143 | } 144 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import { 2 | Platform, 3 | } from 'react-native' 4 | 5 | const Geolocation = Platform.OS === 'android' 6 | ? require('./geoloc') 7 | : navigator.geolocation 8 | 9 | export default Geolocation 10 | -------------------------------------------------------------------------------- /index.js.flow: -------------------------------------------------------------------------------- 1 | // @flow 2 | export type GeolocationReturnType = { 3 | coords: { 4 | latitude: number, 5 | longitude: number, 6 | altitude: number | null, 7 | accuracy: number, 8 | altitudeAccuracy: number | null, 9 | heading: number | null, 10 | speed: number | null, 11 | }; 12 | timestamp: number, 13 | mocked?: boolean, 14 | }; 15 | 16 | export type GeolocationError = { 17 | code: number, 18 | message: string, 19 | PERMISSION_DENIED: number, 20 | POSITION_UNAVAILABLE: number, 21 | TIMEOUT: number, 22 | }; 23 | 24 | export type SuccessCb = (loc: GeolocationReturnType) => void 25 | export type ErrorCb = (err: GeolocationError) => void 26 | 27 | export type LowAccuracyMode = { 28 | /** 29 | * Use this setting to request location precision to within a city block, which 30 | * is an accuracy of approximately 100 meters. 31 | * This is considered a coarse level of accuracy, and is likely to consume less power. 32 | * With this setting, the location services are likely to use WiFi and cell tower 33 | * positioning. Note, however, that the choice of location provider depends on many 34 | * other factors, such as which sources are available. 35 | */ 36 | readonly BALANCED: number, 37 | /** 38 | * Use this setting to request city-level precision, which is an accuracy of 39 | * approximately 10 kilometers. This is considered a coarse level of accuracy, 40 | * and is likely to consume less power. 41 | */ 42 | readonly LOW_POWER: number, 43 | /** 44 | * Use this setting if you need negligible impact on power consumption, but want 45 | * to receive location updates when available. With this setting, your app does 46 | * not trigger any location updates, but receives locations triggered by other apps. 47 | */ 48 | readonly NO_POWER: number, 49 | } 50 | 51 | export type GeolocConfigAndroid = { 52 | /** 53 | * One of Geolocation.LowAccuracyMode 54 | * @default LowAccuracyMode.BALANCED 55 | */ 56 | lowAccuracyMode?: number, 57 | /** 58 | * milliseconds 59 | * @default 10000 60 | */ 61 | fastestInterval?: number, 62 | /** 63 | * milliseconds 64 | * @default 5000 65 | */ 66 | updateInterval?: number, 67 | } 68 | 69 | export type GeolocConfigIOS = { 70 | skipPermissionRequests?: boolean; 71 | } 72 | 73 | export type GeoConfiguration = GeolocConfigAndroid & GeolocConfigIOS; 74 | 75 | export type GeoOptions = { 76 | /** 77 | * Milliseconds. 78 | * @default MAX_VALUE 79 | */ 80 | timeout?: number, 81 | /** 82 | * Milliseconds. 83 | * @default INFINITY 84 | */ 85 | maximumAge?: number, 86 | /** 87 | * Use this setting to request the most precise location possible. 88 | * With this setting, the location services are more likely to use GPS to determine 89 | * the location. 90 | * 91 | * On Android, if the location is cached this can return almost immediately, or it 92 | * will request an update which might take a while. 93 | * 94 | * @default false 95 | */ 96 | enableHighAccuracy?: boolean, 97 | /** 98 | * Distance filter in meters, used only for the watchers. 99 | * @default 100.0 100 | */ 101 | distanceFilter?: number, 102 | /** 103 | * Not used. 104 | */ 105 | useSignificantChanges?: boolean, 106 | } 107 | 108 | declare interface GeolocStatic { 109 | /** 110 | * Sets configuration options that will be used in all location requests. 111 | */ 112 | setRNConfiguration(config: GeoOptions): void; 113 | /** 114 | * Request suitable Location permission based on the key configured on pList. If 115 | * NSLocationAlwaysUsageDescription is set, it will request Always authorization, although if 116 | * NSLocationWhenInUseUsageDescription is set, it will request InUse authorization. 117 | */ 118 | requestAuthorization(): void; 119 | /** 120 | * Invokes the success callback once with the latest location info. 121 | */ 122 | getCurrentPosition(success: SuccessCb, error?: ErrorCb, options?: GeoOptions): void; 123 | /** 124 | * Invokes the success callback whenever the location changes. Returns a watchId (number). 125 | */ 126 | watchPosition(success: SuccessCb, error?: ErrorCb, options?: GeolocOptions): number; 127 | /** 128 | * Clear a watcher. 129 | * @param watchID The ID received from `watchPosition` 130 | */ 131 | clearWatch(watchID: number): void; 132 | /** 133 | * Stops observing for device location changes. In addition, it removes all listeners 134 | * previously registered. 135 | */ 136 | stopObserving(): void; 137 | } 138 | 139 | declare var Geolocation: GeolocStatic; 140 | export default Geolocation; 141 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-cross-geolocation", 3 | "version": "1.1.0", 4 | "description": "React Native Geolocation complatible module that uses the new Google Location API on Android devices.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "react", 11 | "native", 12 | "react-native", 13 | "geolocation", 14 | "location", 15 | "google", 16 | "fused", 17 | "maps" 18 | ], 19 | "author": "aMarCruz ", 20 | "license": "MIT", 21 | "bugs": "https://github.com/aMarCruz/react-native-cross-geolocation/issues", 22 | "homepage": "https://github.com/aMarCruz/react-native-cross-geolocation#README", 23 | "repository": "https://github.com/aMarCruz/react-native-cross-geolocation.git", 24 | "peerDependencies": { 25 | "react-native": ">=0.50.0" 26 | }, 27 | "dependencies": { 28 | "invariant": "^2.2.4" 29 | } 30 | } 31 | --------------------------------------------------------------------------------