Git Product home page Git Product logo

rn-geolocation's Introduction

#RN-Geolocation

NOTE: React Native 0.15 already has the geolocation module implemented for Android.


This package is deprecated as geolocation module was implemented in RN 0.15

Disclaimer: This package is based on code from Corentin Smith. All java files were originally written by him. Kudos to you.

RN-Geolocation is a native module for React Native, that exposes the GoogleApi geolocation. It can be used to determine the users location. This repository contains an example of the code (see last section of this read me), but the package can also be installed on its own.

Installing rn-geolocation in your own project

Before you install this package, be sure that you have installed all tools necessary for React Native Android and the Google Repository and Google Play Services dependency.

To use it do:

npm install --save rn-geolocation

In your settings.gradle replace include ':app' with:

include ':rn-geolocation',':app'
project(':rn-geolocation').projectDir = new File(rootProject.projectDir, '../node_modules/rn-geolocation/android')

In your android/app/build.gradle add:

dependencies {
  ...
  compile project(':rn-geolocation')
}

And finally register the package in your MainActivity.java

...
import com.facebook.soloader.SoLoader;
import com.tiagojdferreira.RNGeolocationPackage; // <-- import

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {

    private ReactInstanceManager mReactInstanceManager;
    private ReactRootView mReactRootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReactRootView = new ReactRootView(this);

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .addPackage(new RNGeolocationPackage()) // <-- import
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        mReactRootView.startReactApplication(mReactInstanceManager, "testGeolocation", null);

        setContentView(mReactRootView);
    }
    ...
}

Now that you've installed it, just require it, and use getCurrentPosition to recover latitude and longitude:

var React = require('react-native');
var rnGeolocation = require('rn-geolocation');

...

rnGeolocation.getCurrentPosition(
      (position) => callback(position)
)

Latitude and longitude can be recovered as:

position.coords.longitude
position.coords.latitude

Running the example

First, clone this repo and go to the example folder and install the project:

git clone https://github.com/Tiagojdferreira/rn-geolocation.git
cd rn-geolocation/example
npm install

npm install may take a while, as react is being installed. Once it is done, to run the app on device, do:

adb reverse tcp:8081 tcp:8081
react-native run-android

rn-geolocation's People

Contributors

rreusser avatar tiagojdf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

rn-geolocation's Issues

Don't run

Hello,i clone this example and my "react-native run-android" successfully build and install my app. But when i try to open program it gets error like this "unable to download JS bundle".What can i do?

Android 6 / API 23

Hi, thank you for making this repository!

I've made some changes to the code because it was failing on Android API level 23 as there is a new permission system: you have to ask for access to the user's location at runtime.

So I had to pass the MainActivity to the module in order to be able to call checkSelfPermission on it.

I added these methods to my MainActivity class

public class MainActivity extends Activity implements
        DefaultHardwareBackBtnHandler,
        ActivityCompat.OnRequestPermissionsResultCallback {
    private static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;

    // ...

    public void checkLocationPermission() {
        // Here, thisActivity is the current activity
        if (!this.hasLocationPermission()) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
            // TODO use ActivityCompat.shouldShowRequestPermissionRationale
        }
    }

    public boolean hasLocationPermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("Permission", "PERMISSION GRANTED");
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    FlurryAgent.logEvent("Location permission denied");
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
        }
    }

And the updated module:

package com.truckfly.rctgeolocation;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableNativeMap;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.truckfly.truckfly.MainActivity;

/**
 * Created by corentin on 10/29/15.
 */
public class GeolocationModule extends ReactContextBaseJavaModule {
    private GoogleApiClient mGoogleApiClient;
    private MainActivity mActivity;

    public GeolocationModule(ReactApplicationContext reactContext, MainActivity activity) {
        super(reactContext);
        mActivity = activity;
    }

    @Override
    public String getName() {
        return "TruckflyGeolocationManager";
    }

    /**
     * @param timeout
     * @param maximumAge
     * @param enableHighAccuracy true -> PRIORITY_HIGH_ACCURACY
     *                           false -> PRIORITY_BALANCED_POWER_ACCURACY
     * @param onSuccess
     * @param onError
     */
    @SuppressWarnings("unused")
    @ReactMethod
    public void getCurrentPosition(final Integer timeout,
                                   final Integer maximumAge,
                                   final Boolean enableHighAccuracy,
                                   final Callback onSuccess,
                                   final Callback onError) {
        if (onSuccess == null) {
            Log.e(getName(), "no success callback");
            return;
        }
        if (onError == null) {
            Log.e(getName(), "no error callback");
            return;
        }

        if (!mActivity.hasLocationPermission()) {
            mActivity.checkLocationPermission();
            onError.invoke();
            return;
        }

        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(getReactApplicationContext())
                    .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle connectionHint) {
                            Log.d(getName(), "onConnected");
                            _getLastKnownLocation(onSuccess, onError, timeout,
                                    maximumAge, enableHighAccuracy);
                        }

                        @Override
                        public void onConnectionSuspended(int cause) {
                            Log.w(getName(), "onConnectionSuspended: " + cause);
                        }
                    })
                    .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult result) {
                            Log.e(getName(), "onConnectionFailed");
                            onError.invoke();
                            mGoogleApiClient.disconnect();
                        }
                    })
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }
        else if (mGoogleApiClient.isConnected()) {
            _getLastKnownLocation(onSuccess, onError, timeout, maximumAge, enableHighAccuracy);
        }
        else {
            mGoogleApiClient.connect();
        }
    }

    private void _getLastKnownLocation(final Callback onSuccess,
                                       final Callback onError,
                                       Integer timeout,
                                       Integer maximumAge,
                                       Boolean enableHighAccuracy) {
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (lastLocation == null) {
            Log.e(getName(), "lastLocation null");
            onError.invoke();
            return;
        }

        Log.d(getName(), "lastLocation found: " + lastLocation.toString());

        WritableNativeMap result = new WritableNativeMap();
        WritableNativeMap coords = new WritableNativeMap();

        coords.putDouble("latitude", lastLocation.getLatitude());
        coords.putDouble("longitude", lastLocation.getLongitude());
        result.putMap("coords", coords);

        onSuccess.invoke(result);
    }

}

It's not perfect but it works (the first call will fail if the permission has not been accepted yet, but the following ones will)

Issue with Android Dependencies

I just struggled to get this working for a while, until I finally figured out that I was missing an Android dependency (Google Repository). Maybe the README should list the necessary SDK modules?

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.