0.0.2 • Published 5 years ago

react-native-trajectory v0.0.2

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

react-native-trajectory

Location tracker module to manage/track user actions on the map related to a direction polyline.

Getting started

# with yarn
yarn add react-native-trajectory

# with npm
npm i react-native-trajectory --save

Setup

Follow the following steps to setup the trajectory event emitter tracker.

1. Import package

import {Tracker, EVENT, MapUtils} from 'react-native-trajectory'

2. Setup a new instance of the tracker

Globally on the top of your component add the following

const tracker = new Tracker()
let trackingData = tracker.constructTrackingObject()
 //reference to `this` of the component. In case you want to update state!
let componentContext; //let's just call it context :P

// const store = ...

3. Set a reference to this of the component

Only use in case of making changes in the component. Like setting the state from inside the trajectory tracker!

 componentDidMount() {
    componentContext = this
  }

4. Configure the data store that keeps track of the trajectory tracker data

Just bellow the tree lines of code of Step 2 add the following store configuration.

//... bellow Step 2 

const store = tracker.observe(trackingData, events => {
  events && events.forEach(event => {
      //in case you want events stored on the components state
      componentContext.setState({events})
      switch (event) {
        case  EVENT.STARTED_NEW_TRACT_TRAJECTORY:
          console.log('User tracking started')
          break
        case  EVENT.MOVING_TOWARDS_NEXT_DESTINATION_MARKER:
          // user is moving to the correct direction
          break
        case  EVENT.MOVING_AWAY_NEXT_DESTINATION_MARKER:
          console.log('Where are you going?!')
          break
        case  EVENT.REACHED_MARKER_AFTER_NEXT_DESTINATION_MARKER:
          console.log('SKIPPED STEP')
          store.activePolylineStep += 2 //skipped one step
          break
        case EVENT.REACHED_NEXT_DESTINATION_MARKER:
          if (store.polyline && store.activePolylineStep >= store.polyline.length) {
            //we are at the last marker
            console.log('Congrats! You`ve reached your destination!')
          } else {
            // showSnack('go to next polyline step')
            console.log('go to next polyline step')
            // go to next step
            store.activePolylineStep += 1
            console.log(store.activePolylineStep)
            //show turn info for the user
          }
          break
        case EVENT.END_LOCATION_REACHED:
          //final destination reached
          console.log('Congrats! You`ve reached your destination!')
          tracker.reset(store)
          break
        case EVENT.MOVING_AWAY_FROM_POLYLINE:
          console.log('The road is the other WAY!\nIdiot!')
          break
        case EVENT.APPROACHING_POLYLINE:
          console.log('You are on the right track!')
          break
        case EVENT.MOVING_CLOSER_TO_NEXT_POLYLINE:
          //taking shortcut
          console.log('Taking a shortcut! Clever!')
          break
      }
    }
  )
})

CAUTION! Make sure you dont remove the incrementation lines from the above code. Those line are responsible for specifying which step of the polyline the package will provide events for.

5. Set a polyline to the tracker.

    /**
     * routeInfo => Json response from Google Maps api for directions between two locations
     * 
     * Docs {@link https://developers.google.com/maps/documentation/directions/start}
     * Docs {@link https://developers.google.com/maps/documentation/directions/intro}
     */
    const routeInfo = {}
    
    //build polyline step by step
    const polylineSteps = MapUtils.buildPolylineSteps(routeInfo)

    //when the we start tracking on the map, update the location observer module
    //reset the store if there are old info for directions
    store.polyline = polylineSteps  //polyline info
    store.activePolylineStep = 0 //default step 0 (index)
    tracker.reset(store) // call a reset for the tracker just in case you have previous data applied to it.

6. Connect location changes to trajectory tracker

The following code is based on the demo implemented in the example app, but you can use your own location tracking way to update the tracker data.

//Used package
import Geolocation from '@react-native-community/geolocation'

//somewhere inside the component
 Geolocation.watchPosition((position) => {
            let region = {
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
              latitudeDelta: 0.00922 * 1.5,
              longitudeDelta: 0.00421 * 1.5
            }

            if (region && region.latitude && region.longitude)
              store.location = {...region}
          }

In case of errors check the example app in this repository!

Helpful methods

  • MapUtils.extractPolylineFromMock(routeDetails) (Array) - Extract polyline points from google api response. Return array of location objects. {latitude: double, longitude: double}
  • MapUtils.buildPolylineArray(gpsLocation, destinationMarker, polyline) (Array) - Build a google maps polyline array including the start and end GPS locations as well as all the points of the polyline. polyline can be created using the extractPolylineFromMock() method.
  • MapUtils.buildPolylineSteps(routeInfo) (Array) - Build a google maps polyline steps directly from the Google maps directions JSON response.
  • tracker.observe(trackingData, callback) (Function) - Method to initialize the trajectory tracker observer and event emitter. Params:
    • trackingData => Object construct the package needs to store the data, can be accessed from outside the package if needed.
    • callback => Callback that emits events from the trajectory tracker package. Events are determined based on a probability approach.
  • MapUtils.reset(store) (Function) - Reset the tracking data from the tracing data cache. The package uses an internal data cache to calculate the probabilities of events happening (Emitted events).

How to run the example app

To run the example app in this repo make sure you create the credentials.js file inside the example/app/lib/ directory. Follow the example of .credentials.js and add you Google Maps key. Also add the key to the AndroidManifest.xml file if you are running on Android.

License MIT

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.