React Native Maps with Google Directions Api

We have to use an external service to draw real world directions between two (or more) locations on the Map. For React Native, i ended up using both react native maps and Google Directions Api.

We have to use an external service to draw real world directions between two (or more) locations on the Map. For React Native, i ended up using both react native maps and Google Directions Api.

React Native Maps

Thanks to folks at airbnb, we have react-native-maps: A complete set of React components for Maps. You can check features and details from Github repo:

airbnb/react-native-maps
_react-native-maps - React Native Mapview component for iOS + Android_github.com

Google Directions Api Service

Google provides Directions API that calculates directions between locations. Since It is an api-based service, there is no SDK for any platform (not officially at least)

Before Start Coding

The JSON response returned from Directions Api contains a key named overview_polyline which is an encoded polyline looks like this:

1
cxftF{xcpDEt@Kj@Gf@E`C@~@XtAJb@Jh@@J@D?F@HA\Ip@Ox@KZKh@?PAB@D?H?B@F@B?F@@@DBBBD@@B@@@B@D@B@D?L@v@FFBXDpFxA|@l@^d@z@~BVz@Nf@Ph@DNFLLXVZxArAh@b@l@d@r@l@pAzAl@z@PXBF@FBD@F@F?H?D@JCLCHA@A@A@A@C@IBQBKAYIWSMKKMGKOOMIo@D]FSBi@JSDUAs@Qm@WcBk@s@U[K\_@Sq@e@OUMWKQMUKMIGMGICC?E?K?E@QHUNm@Xq@XYLa@Ls@LYDW@SDGBG@IHS\Wl@EFA@A@CDEDEBG@C@[?e@Ca@KQGa@QSC\_@?Y@k@Fu@As@?U@I@I@IBEBQH]Lq@\WLuBx@i@Vy@TaANK@E@QAICUKIGMM]e@OWISEOCSAMAG

This is the data we are going to use to create our route on the map. But first we need to decode it. There is a small library from MapBox team named Polyline:

mapbox/polyline
_polyline encoding and decoding in javascript_github.com

We can use this library to encode / decode polylines.

Example App

Create a new react native app:

1
$ react-native init RnDirectionsApp

Inside RnDirectionsApp folder, install react-native-maps and polyline :

1
2
$ npm install react-native-maps @mapbox/polyline --save  
$ react-native link

You can find more detailed installation guide here at Github Repo

Now we have an empty but ready react-native app. Let’s first see our getDirections method:

Simply, this method:

  • Fetches directions data from Google (line 4)
  • Decodes encoded polyline data ( line 6 )
  • Converts decoded polyline data into a list of objects (line 7)
  • Updates state with new coords data

Now we can draw our route on the map. To do this, We can use MapView.Polyline from react-native-maps. In our render method:

You can find more info on detailed usage of Mapview.Polyline here.

And this is full version of index.ios.js :

Hope this helps. Please leave a comment for any kind of feedback

UPDATE: Bram Van Damme created a component based on this post. Looks promising. You can check it from here:

bramus/react-native-maps-directions