Coder Social home page Coder Social logo

react-native-maps-directions's Introduction

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.

react-native-maps-directions's People

Contributors

alioguzhan avatar bramus avatar briangonzalez avatar capjavert avatar chitova263 avatar code-smith avatar dependabot[bot] avatar jamies1211 avatar karimcambridge avatar luispeerez avatar matan18 avatar mateosilguero avatar methodbox avatar oe-dev avatar petrux25 avatar protyze avatar ralph-dev avatar rodneyonyi avatar rohitbansa avatar thousight avatar tteke avatar tuononh avatar xiaoxu193 avatar yoavprat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-maps-directions's Issues

Dynamic rerendering

Hi @bramus ! We use a fork of this module to build dynamic routes, depending on user's position. And now, if user changes it, the code resets current state and waits for google's response to get new coordinates. But is it necessary to reset the state? This logic causes blinking of a polyline (because there is a small time interval between the reset of the state and displaying a new polyline).
Anyway, thanks for the great work you have done!

Animate Polyline

hi! do you think its possible to animate the polyline between 2 markers like actually uber does it?
Thanks!!

'Yarn' is not recognized.

I utilized the command provided in the instruction: yarn add react-native-maps-directions in the Node.js command prompt.

However, it gives the result: 'yarn' is not recognized as an internal or external command, operable program or batch file.

Please Help

I am new to all of this programming stuff.

Get directions Android Physical device

When trying to get directions between 2 points i seem to get a response from Google Directions API. But my console logs this error

--------- beginning of crash 02-16 12:07:46.385 10186-10186/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.Paxi, PID: 10186 com.facebook.react.bridge.UnexpectedNativeTypeException: Tried to read an int, but got a non-integral double: 20.571429

Any idea on this? this is when running on android physical device

I am using it for direction in my app maps it is working fine in android but not in ios no error got

i am using this as child of MapView

<MapViewDirections
                        origin={value[0]["coordinates"]}
                        destination={value[1]["coordinates"]}
                        waypoints={(value.length > 2) ? value.slice(1, -1) : null}
                        apikey={settings.GOOGLE_MAPS_APIKEY}
                        strokeWidth={5}
                        strokeColor={color}
                        onStart={(params) => {
                          if (__DEV__)console.log(`Started routing between "${params.origin}" and "${params.destination}"`);
                        }}
                        onReady={(result) => {
                          this.mapView.fitToCoordinates([
                            this.state.markers[0]["coordinates"],
                            this.state.markers[1]["coordinates"]
                          ], {
                              edgePadding: {
                                right: parseInt(width / 20),
                                bottom: parseInt(height / 20),
                                left: parseInt(width / 20),
                                top: parseInt(height / 20),
                              }
                            });
                        }}
                        onError={(errorMessage) => {
                          if (__DEV__)console.log('757 GOT AN ERROR', errorMessage);
                        }}
                      />

Flights transportation mode not supported

This API support the use of the DirectionsService object to fetch directions for different travel modes. BUT, it doesn't support the flights travel mode.
So is their any way to do this.
THNX in advance.

showsTraffic causes iOS app crashing

Hi,

I'm using the props showsTraffic and mapLayer on MapView but when I toggle between 'standard' and 'satellite' and then click on the button with showsTraffic prop the app crashes on iOS but it works fine on Android

How to integrate/make use of the code

I am having trouble understanding how to make use of the react-native-maps-direction code here and or other react-native code/code samples.

I followed the steps on the React Native website (Getting Started).

It resulted as it said it would, a project/module named AwesomeProject. Within that, is a file named App.js which was generated with the whole set up/configuration process and not by me.

NOW...

Is it that I just copy and paste the contents of react-native-maps-direction code sample into AwesomeProject? or is it that I open the contents of the react-native-maps-direction code sample with the Atom Editor? or is there some other step?

different route colors

How can i set different colors for each path? for example a to b (red). b to c (blue)...

<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} pinColor={this.state.colors[index]} /> ))} {this.state.coordinates.length >= 2 && ( <MapViewDirections origin={this.state.coordinates[0]} waypoints={ this.state.coordinates.length > 2 ? this.state.coordinates.slice(1, -1) : null } destination={ this.state.coordinates[this.state.coordinates.length - 1] } apikey={GOOGLE_MAPS_APIKEY} strokeWidth={3} strokeColor= {this.state.colors[this.state.coordinates.length - 1]} onReady={result => { this.mapView.fitToCoordinates(result.coordinates, { edgePadding: { right: width / 20, bottom: height / 20, left: width / 20, top: height / 20 } }); }} /> )} </MapView>

this code colorizes the whole path from a to c

Can it work with dynamic marker ?

Hi,
Can and How i use dynamic marker with your directions ?
Example: After i search and set markers for search locations.
Thank you.

Fit direction into map

I need MapView to zoom and display the direction fully in screen. Is there anyway to let MapView knows the boundary of rendered direction to fit it into map?

Distance and Time?

Is there a way to get the distance of the route and the time it will take to make the drive? This would be a game changer.

how to draw direction between multiple points ?

how can i draw line between multiple points on map instead of origin to destination actually i am working on tracking application where i have multiple locations from where user passes so how can i draw it between multiple points ?

Animate drawing of the polyline

Hi,

How could you animate the drawing of the polyline when the directions are returned? I would like to make it look like someone's almost drawing the directions with a pen.

Apart from that....thanks very much for this. It saved me a couple of hours doing it myself.

Unmouting while a fetch is still in progress yields a warning

You'll get an error like this:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the MapViewDirections component.

This is due setState() being called in the fetch promise handler, while the component has already been unmounted.

On the web an abortable fetch is available, which can be polyfilled.

If that won't work with React Native, other possible approaches could be:

Question about the call API

Is the call API to Google is send every time the position of the user change ? (origin)

ps : My destination don't change

MapViewDirections Error: This IP, site or mobile application is not authorized to use this API key. Request received from IP address 1.42.189.121, with empty referer

i have created GOOGLE_MAPS_APIKEY and added in app but i am warning and not able to see direction in map . here is code

<MapViewDirections
origin={origin}
destination={destination}
apikey={GOOGLE_MAPS_APIKEY}
strokeWidth={3}
strokeColor="hotpink"

/>
warnning : MapViewDirections Error: This IP, site or mobile application is not authorized to use this API key. Request received from IP address 1.42.189.121, with empty referer

Navigation with dots not just a stroke

Hi @bramus,

I was checking the code, and I noticed that the only option for drawing the rote between two coordinates is a whole stroke, but not Dots or any other type. I saw that the MapViewDirections properties are bind with interface MapPolylineProps which supports only:

         strokeWidth?: number;
         strokeColor?: string;
         <MapViewDirections
                             strokeWidth={5}
                             strokeColor="orange"
         ...

Can this be extended to support more than one type of path (stroke): ?

         navigationPathType?: stroke | dots | whatever
         navigationPathWidth?:  number
         navigationPathColor?:  string

Regards,

V. Nguyen

Tag showing distance

I am displaying a route using react-native-maps-direction between two locations in react-native-maps.

How can i show distance, after user clicks on polyline
Im done with calculations and im getting the distance in meters, im asking that if user clicks on polyline how do i show this distance to user...

Any code i am missing out???

Failed to execute 'readAsText' on 'FileReader'.

Hi, I tried to use this component, and I currently getting the following error:
MapViewDirections Error: TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.

At the beginning I thought It was my mistake, but I tried to reproduce the Extended example and I am still getting the same error.

how to get EAT (estimated arrival time)

iam trying to build navigation app which shows the nearest vehicle and it's expected arrival time.
does the package provide such function, and if not is there any other way?

Support waypoints

Hi, are you planning to extend this component to support waypoint to create the route with array of points.

Thanks in advanced!!!

Warning: Failed prop type: Invalid prop `destination` supplied to `MapViewDirections`

<MapView
  region={{
	latitude: this.state.location.latitude,
	longitude: this.state.location.longitude,
	latitudeDelta: LATITUDE_DELTA,
	longitudeDelta: LONGITUDE_DELTA,
  }}
  onRegionChange={this.onRegionChange}
  initialRegion={{
	latitude: this.state.location.latitude,
	longitude: this.state.location.longitude,
	latitudeDelta: LATITUDE_DELTA,
	longitudeDelta: LONGITUDE_DELTA,
  }}
  onMapReady={Platform.OS === 'android' ? this.onMapLayout : null}
  onLayout={Platform.OS === 'ios' ? this.onMapLayout : null}
  mapType='standard'
  showsCompass
  showsBuildings>
  { this.state.isMapReady &&
	<MapViewDirections
	  origin={this.state.location}
	  destination={this.state.destination}
	  apikey={this.state.maps_apikey}
	  strokeWidth={3}
	  strokeColor="blue"
	/>
  }

</MapView>

this returns:
Warning: Failed prop type: invalid prop destination supplied to MapViewDirections.

This is a bug? Any solution?

How to make the view always visible with the 2 points?

Example. I am rendering 2 points.. but I want the zoom to always show the 2 points. So I need to adjust. I am not sure what calc is that or if it's too complicate.

This is the map:

image

What would be the calc to always show the 2 points? :}

Getting not authorized access when using this module

I am using the react-native-maps and it's already working, but when I try to use the same key using this module, I am getting this message:

image

<MapViewDirections
          origin={origin}
          destination={destination}
          apikey={GOOGLE_MAPS_APIKEY}
        />

Show public transport names as waypoints in transit mode

In "transit mode" the line is rendered correctly following the intersection of different public transports, but there is no way to distinguish them from each other, there is only one flat line. Does anyone know how to achieve this with waypoints or something, like in google maps website? Thanks!

captura de pantalla 2018-04-20 a la s 00 39 37

Snap to road?

Add option for snap to road for better polyline support. I can help with this if needed.

Feature Request : MapView Zoom Level

Can you add fItToSuppliedMarkers support in this package so that the mapview can have the Source/origin & the destination visible in the same mobile view . where the markers can be pointing to origin & destination address/location ?

onReady issue

I don't know why if I want to set variables in onReady, it will goes to an infinity loop, however if I just use console.log, it is alright, here is the code. The code should not affected the origin and destinaiton.

    <MapViewDirections
        origin={{latitude:this.state.startLatitude,longitude:this.state.startLongitude}}
        destination={{latitude:this.state.endLatitude,longitude:this.state.endLongitude}}
        mode='driving'
        language='en'
        strokeWidth={4}
        strokeColor="black"
        onReady={(result) => {
             //this.setDistance(result.distance,result.duration_in_traffic)
         }}
        onError={(errorMessage) => {
            //console.log(errorMessage);
          }}
    />

setDistance(distance,duration_in_traffic){
    this.setState({distance:parseFloat(distance),durationInTraffic:parseInt(duration_in_traffic)});
}

Add language param

First, thank you for this plugin! This really awesome!

It would be nice to be able to add the language as a parameter to make the call to the api directions. Since in localities in Latin, it does not work correctly, for example:

https://maps.googleapis.com/maps/api/directions/json?origin=Cedillo&destination=Sepulveda&key=AIzaSyDFWLilTrTTDGH1uCorU7m7RP7W9ynlPQk&mode=driving

instead, if this works

https://maps.googleapis.com/maps/api/directions/json?origin=Cedillo&destination=Sepulveda&key=AIzaSyDFWLilTrTTDGH1uCorU7m7RP7W9ynlPQk&mode=driving&language=es

Thanks again!

Network request failed

I have a problem the map shows but i get a warning in my IOS simulator that the Network Request failed? When i inspect in the remote debugger the api of google directions gets called and there is a response. Any idea what could be wrong?

Duration and distance for waypoints.

The waypoint feature is awesome! Can you also expose the Duration and distance to each waypoint in the callback for onReady?
I believe Google's direction API response already contains that information.

Thanks for a great library!

New feature: Animated directions/polyline

Thanks for taking the time to put this library together saved me a ton!

I wish to add additional functionality to this library to allow the drawing of the directions to be animated. Let me know if you would be willing to accept this change.

Can't see the directions on iOS

I am unable to see directions on iOS, I am using a child element on parent map, to generate markers and get them directions.

Somehow it shows me the markers but not the directions (Btw onReady event works perfectly)

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.