• Stars
    star
    1,219
  • Rank 38,465 (Top 0.8 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Directions Component for `react-native-maps`

react-native-maps-directions

npm Version npm Downloads Contributors GitHub Last Commit License

Directions component for react-native-maps – Draw a route between two coordinates, powered by the Google Maps Directions API

react-native-maps-directions

Installation

Install react-native-maps-directions as a dependency using either

  • Node's npm

    npm install react-native-maps-directions
    
  • Yarn

    yarn add react-native-maps-directions
    

Basic Usage

Import MapViewDirections and render it as a child of a MapView component. The mandatory MapViewDirections props are:

  • origin: The origin location to start routing from
  • destination: The destination location to start routing to
  • apikey: Your Google Maps Directions API Key (request one here; if you're using an existing Google Maps API Key make sure you've enabled the Google Maps Directions API for that key using the Google API Console).
import MapViewDirections from 'react-native-maps-directions';

const origin = {latitude: 37.3318456, longitude: -122.0296002};
const destination = {latitude: 37.771707, longitude: -122.4053769};
const GOOGLE_MAPS_APIKEY = '…';

<MapView initialRegion={…}>
  <MapViewDirections
    origin={origin}
    destination={destination}
    apikey={GOOGLE_MAPS_APIKEY}
  />
</MapView>

Once the directions in between destination and origin has been fetched, a MapView.Polyline between the two will be drawn. Whenever one of both changes, new directions will be fetched and rendered.

Component API

Props

Prop Type Default Note
origin LatLng or String The origin location to start routing from.
destination LatLng or String The destination location to start routing to.
apikey String Your Google Maps API Key (request one here; if you're using an existing Google Maps API Key make sure you've enabled the Google Maps Directions API for that key using the Google API Console by hitting the β€œEnable APIs and Servicesβ€œ button).
waypoints [LatLng or String] [] Array of waypoints to use between origin and destination.
language String "en" The language to use when calculating directions. See here for more info.
mode String "DRIVING" Which transportation mode to use when calculating directions. Allowed values are "DRIVING", "BICYCLING", "WALKING", and "TRANSIT". (See here for more info).
resetOnChange boolean true Tweak if the rendered MapView.Polyline should reset or not when calculating the route between origin and destionation. Set to false if you see the directions line glitching.
optimizeWaypoints boolean false Set it to true if you would like Google Maps to re-order all the waypoints to optimize the route for the fastest route. Please be aware that if this option is enabled, you will be billed at a higher rate by Google as stated here.
splitWaypoints boolean false Directions API has a limit of 10 or 25 (depends on the billing plan) waypoints per route. When exceeding this limit you will be billed at a higher reate by Google. Set this to true if you would like to automatically split waypoints into multiple routes, thus bypassing this waypoints limit.
directionsServiceBaseUrl string (Google's) Base URL of the Directions Service (API) you are using. By default the Google Directions API is used ("https://maps.googleapis.com/maps/api/directions/json"). Usually you won't need to change this.
region String If you are using strings for origin or destination, sometimes you will get an incorrect route because Google Maps API needs the region where this places belong to. See here for more info.
precision String "low" The precision level of detail of the drawn polyline. Allowed values are "high", and "low". Setting to "low" will yield a polyline that is an approximate (smoothed) path of the resulting directions. Setting to "high" may cause a hit in performance in case a complex route is returned.
timePrecision String "none" The timePrecision to get Realtime traffic info. Allowed values are "none", and "now". Defaults to "none".
channel String null If you include the channel parameter in your requests, you can generate a Successful Requests report that shows a breakdown of your application's API requests across different applications that use the same client ID (such as externally facing access vs. internally facing access).

More props

Since the result rendered on screen is a MapView.Polyline component, all MapView.Polyline props – except for coordinates – are also accepted.

<MapView initialRegion={…}>
  <MapViewDirections
    origin={origin}
    destination={destination}
    apikey={GOOGLE_MAPS_APIKEY}
    strokeWidth={3}
    strokeColor="hotpink"
  />
</MapView>

An extra note on origin and destination

The values for the origin and destination props can take several forms. They can either be:

  • Coordinates in the form of an object with latitude and longitude keys
  • Coordinates in the form of a string with latitude and longitude values separated by a comma
  • Strings representing an address
  • Strings representing a location
  • Strings containing a Place Id from the Google Maps Place API prefixed with place_id:

All examples below have the same origin location, represented in the formats mentioned above:

<MapViewDirections origin={{ latitude: 37.3317876, longitude: -122.0054812 }} destination="…" />
<MapViewDirections origin="37.3317876,-122.0054812" destination="…" />
<MapViewDirections origin="Apple Park Visitor Center" destination="…" />
<MapViewDirections origin="10600 N Tantau Ave, Cupertino, CA 95014, USA" destination="…" />
<MapViewDirections origin="place_id:ChIJW5i0tJC1j4ARoUGtkogTaUU" destination="…" />

Note: The origin and destination props don't need to use the same representation, you may mix them.

Tip: Don't forget to tweak the language prop when using localized location names.

Events/Callbacks

Event Name Returns Notes
onStart { origin, destination, waypoints: [] } Callback that is called when the routing has started.
onReady { distance: Number, duration: Number, coordinates: [], fare: Object, waypointOrder: [[]] } Callback that is called when the routing has succesfully finished. Note: distance returned in kilometers and duration in minutes.
onError errorMessage Callback that is called in case the routing has failed.

Extended Example

This example will draw a route between AirBnB's Office and Apple's HQ

import React, { Component } from 'react';
import { Dimensions, StyleSheet } from 'react-native';
import MapView from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';

const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.771707;
const LONGITUDE = -122.4053769;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;

const GOOGLE_MAPS_APIKEY = '…';

class Example extends Component {

  constructor(props) {
    super(props);

    // AirBnB's Office, and Apple Park
    this.state = {
      coordinates: [
        {
          latitude: 37.3317876,
          longitude: -122.0054812,
        },
        {
          latitude: 37.771707,
          longitude: -122.4053769,
        },
      ],
    };

    this.mapView = null;
  }

  onMapPress = (e) => {
    this.setState({
      coordinates: [
        ...this.state.coordinates,
        e.nativeEvent.coordinate,
      ],
    });
  }

  render() {
    return (
      <MapView
        initialRegion={{
          latitude: LATITUDE,
          longitude: LONGITUDE,
          latitudeDelta: LATITUDE_DELTA,
          longitudeDelta: LONGITUDE_DELTA,
        }}
        style={StyleSheet.absoluteFill}
        ref={c => this.mapView = c}
        onPress={this.onMapPress}
      >
        {this.state.coordinates.map((coordinate, index) =>
          <MapView.Marker key={`coordinate_${index}`} coordinate={coordinate} />
        )}
        {(this.state.coordinates.length >= 2) && (
          <MapViewDirections
            origin={this.state.coordinates[0]}
            waypoints={ (this.state.coordinates.length > 2) ? this.state.coordinates.slice(1, -1): undefined}
            destination={this.state.coordinates[this.state.coordinates.length-1]}
            apikey={GOOGLE_MAPS_APIKEY}
            strokeWidth={3}
            strokeColor="hotpink"
            optimizeWaypoints={true}
            onStart={(params) => {
              console.log(`Started routing between "${params.origin}" and "${params.destination}"`);
            }}
            onReady={result => {
              console.log(`Distance: ${result.distance} km`)
              console.log(`Duration: ${result.duration} min.`)

              this.mapView.fitToCoordinates(result.coordinates, {
                edgePadding: {
                  right: (width / 20),
                  bottom: (height / 20),
                  left: (width / 20),
                  top: (height / 20),
                }
              });
            }}
            onError={(errorMessage) => {
              // console.log('GOT AN ERROR');
            }}
          />
        )}
      </MapView>
    );
  }
}

export default Example;

Example App

An example app can be found in a separate repo, located at https://github.com/bramus/react-native-maps-directions-example.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Credits

This code is inspired upon the article React Native Maps with Google Directions Api by Ali Oğuzhan Yıldız.

License

The MIT License (MIT). Please see License File for more information.

More Repositories

1

router

A lightweight and simple object oriented PHP Router
PHP
1,085
star
2

mixed-content-scan

Scan your HTTPS-enabled website for Mixed Content
PHP
522
star
3

photoshop-google-maps-tile-cutter

PS_Bramus.GoogleMapsTileCutter - A Photoshop script that cuts image tiles from any image for direct use with Google Maps
JavaScript
201
star
4

js-pagination-sequence

Generate a sequence of numbers for use in a pagination system, the clever way.
JavaScript
140
star
5

monolog-colored-line-formatter

Colored/ANSI Line Formatter for Monolog
PHP
132
star
6

freshinstall

Automatically configure and install software onto your new Mac
Shell
106
star
7

composer-autocomplete

Bash/Shell autocompletion for Composer
94
star
8

mastodon-redirector

View Mastodon profiles on your Mastodon instance
JavaScript
93
star
9

ansi-php

ANSI Control Functions and ANSI Control Sequences (Colors, Erasing, etc.) for PHP CLI Apps
PHP
89
star
10

specificity

JavaScript Package to calculate the Specificity of CSS Selectors
JavaScript
68
star
11

viewport-resize-behavior

Viewport vs Virtual Keyboard Resize Behavior Explainer
45
star
12

simple-rest-api-explorer

A simple way to showcasing and exploring all endpoints of your RESTful API.
JavaScript
37
star
13

mercator-puzzle-redux

Dynamic take on the original Mercator Puzzle by Google
HTML
37
star
14

scroll-driven-animations-debugger-extension

Browser extension to debug Scroll-Driven Animations
36
star
15

ion-drawer-vertical

A vertical drawer for Ionic 1
JavaScript
35
star
16

sda-utilities

Collection of utility functions for use with Scroll-Driven Animations
JavaScript
28
star
17

style-observer

MutationObserver for CSS
TypeScript
26
star
18

view-transitions-demos

HTML
20
star
19

react-native-maps-directions-example

Example app that uses react-native-maps-directions
Java
20
star
20

ws2-sws-course-materials

Course materials for the course Serverside Webscripting, part of the Professional Bachelor ICT study programme.
PHP
13
star
21

chrome-dark-mode-toggle

Real control over Light Mode / Dark Mode on a per-site basis!
13
star
22

web-dev-rss

Cloudflare Worker that generates RSS Feeds for web.dev
JavaScript
12
star
23

webhid-elgato-stream-deck-daft-punk-soundboard

WebHID Demo: Elgato Stream Deck Daft Punk Soundboard
JavaScript
12
star
24

bramus_cssextras

bramus_cssextras is a plugin for TinyMCE which enables the usage of CSS classes and CSS ids on any HTML element within TinyMCE. Together with an external CSS file, set via the TinyMCE content_css setting, bramus_cssextras bridges the (visual) gap between the content entered through TinyMCE and the actual output
JavaScript
12
star
25

ria-course-materials

Course materials for the course Web & Mobile Development (formerly Rich Internet Applications), part of the Professional Bachelor ICT study programme.
JavaScript
12
star
26

ws1-sws-course-materials

Course materials for the course Serverside Webscripting, part of the Professional Bachelor ICT study programme.
PHP
11
star
27

css-houdini-voronoi

A CSS Houdini Paint Worklet that draws a Voronoi Diagram as a background image
JavaScript
10
star
28

google-maps-polygon-moveto

Programmatically move a google.maps.Polygon to a new google.maps.LatLng using Google Maps V3
JavaScript
9
star
29

js-range

JavaScript
7
star
30

ws2-sws-fiddles-silex

Silex Code Examples/Fiddles
PHP
7
star
31

css-houdini-circles

A CSS Houdini PaintWorklet to draw background circles.
JavaScript
7
star
32

PS_BRAMUS.TextConvert

PSD2TXT and TXT2PSD for the masses!
JavaScript
6
star
33

enumeration

Yet Another Enumeration Implementation for PHP
PHP
5
star
34

chrome-for-developers-rss

Cloudflare Worker that generates RSS Feeds for developer.chrome.com
JavaScript
4
star
35

wec-web-ui-summit-2023-demos

WEC Web UI Summit 2023 Demos
HTML
4
star
36

reflection

A library that tries to make PHP's built-in Reflection better.
PHP
3
star
37

github-toggle-chrome-extension

Quickly toggle between a GitHub Repo and its GitHub Pages
JavaScript
3
star
38

jquery_classdata

jQuery ClassData is a jQuery plugin that allows you to access and manipulate data saved in the class property of DOM-elements in a nice and easy to use way.
JavaScript
3
star
39

js-pagination-sequence-demos

Demos that use @bramus/pagination-sequence
JavaScript
2
star
40

css-selector-benchmark

CSS Selector Benchmarks, using PerfTestRunner and Puppeteer
HTML
2
star
41

wmd-course-materials

Course materials for the course Web & Mobile Development, part of the Professional Bachelor ICT study programme.
JavaScript
2
star
42

yummy

A self hosted Delicious (with del.icio.us import)
PHP
1
star
43

meetingzone

Find a meeting time across timezones
JavaScript
1
star
44

gcloud-kms-scripts

A collection of scripts here to help interact with Google's Cloud Key Management Service (KMS)
Shell
1
star
45

tokenphrase

TokenPhrase is a PHP class that generates unique phrases for you to use in your app as tokens
PHP
1
star
46

terraform-gcloud-event-cloud-function

Terraform deploy a local folder to a Google Cloud Function that can be triggered via an Event
HCL
1
star
47

remix-example-app

JavaScript
1
star
48

parcel-css-demo

JavaScript
1
star
49

bramus_cssextras-demo

Demo for bramus_cssextras (https://github.com/bramus/bramus_cssextras) | bramus_cssextras is a plugin for TinyMCE which enables the usage of CSS classes and CSS ids on any HTML element within TinyMCE. Together with an external CSS file, set via the TinyMCE content_css setting, bramus_cssextras bridges the (visual) gap between the content entered through TinyMCE and the actual output
1
star