This is part 2 of how to add polylines to your react-native app using Google Directions API. This tutorial will focus on creating a project on Google cloud console and then using the Google directions API ( and the API key we retrieve from the Google cloud console) to draw a polyline from our users location to another destination.

First thing we need to do is create a project on Google cloud console. Google cloud console can be seen as a management tool for a lot of resources that can integrate into your software, it handles various aspects of applications including databases, API keys and client secrets.

We need to go to the link below.

You will need to sign in with one of your google accounts, once you have done this you should see a piece of text labelled “Select a project”, click this and a pop up should show listing your previous projects and allowing you to make another one (unless you have exceeded your allocated quota of projects). Click on “NEW PROJECT”

You will then need to give your project a name, name it something like “polyproject” and leave the “location/organisation” textbox as it is. It will take a few seconds for your project to create and you should a notification underneath the notification bell to say it has been created, click this notification to be redirected to the project.

Now click on the hamburger menu on the top left of the page and then click “APIs & services”, then click on the “credentials” tab on the left hand side.

Click on the “Create credentials” box and click on “API key”, this will generate an API key to use to make requests to the Google directions API.

Once you do this a small box will come up showing the API key, copy this into somewhere safe.

Our next step is to enable the use of the Google directions API, to do this click on the “Library” tab which is above “credentials” on the left hand side, this will open a page like the below.

Enter in the search box “google directions”

Click on the first result, this will open another page explaining the API, click on the button labelled “Enable”.

This will then enable the API for use and redirect you to the home page of your project. Once again I will say, you must keep this API key safe and do not share it with anybody who you do not trust, I will be adding the API key to the project just for this tutorial but would never do this for a production ready app.

If you wish to make more than 1 request to this API you are required to add a billing account to your Google cloud console account, a full walkthrough of this is out of scope for this tutorial, however, to add this billing account you will need to click on the hamburger menu on the top left of the page and then click on the tab labelled “Billing”.

This will then give you an option to add or manage billing accounts depending on whether you have added one previously, you will need to add your card details and can set budgets like £20 a month, I believe Google directions API charges $5 per 1000 requests, however, I am not a lawyer or Google advisor so it is up to you whether you want to proceed with adding your card details or not.

After you have done this we will go back to our project and create a file called keys.js in the root of our project and fill it with the below.

module.exports = {gapikey: 'myapikeyhere'}

Obviously replace ‘myapikeyhere’ with your api key generated earlier, however, keep the single quotes.

This will enable us to export the api key and access it in other files via importing.

We now need to install one of my favourite packages called “axios”, this is a http client used to make requests and get responses from urls it is incredibly handy as you can make simultaneous requests and uses promises.

To install, enter the command below.

npm install axios

In addition, we will need to install another package in order to retrieve our users location details, this package is called “react-native-community/geolocation” and contains methods from the Geolocation API.

npm install @react-native-community/geolocation --save

After installing this you will need to install the missing dependencies for Pods. Use the command below to do this.

cd ios && pod install

Now close and restart your simulator and terminal for the changes to take effect and enter the below to go back to the root of your project.

cd ..

Our next step is to add a state object to our “App.js” file like the below. Each of these will contain the user latitude and longitude retrieved from the Geolocation package we have just installed.

state = {userLat:0.0,userLng:0.0}

You will then need to use the lifecycle method “componentDidMount” so we can get the users location on load of the component and set the state, in addition, we will need to import the Geolocation API from our newly installed package using the below.

import Geolocation from '@react-native-community/geolocation';

We will need to get the users current location and use its values returned in the callback using the method “getCurrentPosition” which is accessed like so “Geolocation.getCurrentPosition”, the method takes a callback and I have named mine “position” this will contain information such as latitude and longitude that we will use in conjunction with the Google directions API. Below is our componentDidMount method currently.

componentDidMount(){Geolocation.getCurrentPosition(position=>{alert(position.coords.latitude + ' ' + position.coords.latitude )})}

We will then set the state equal to the position.coords.latitude and longitude properties so we can use these later.

componentDidMount() {Geolocation.getCurrentPosition(position => {this.setState({userLat: Number(position.coords.latitude),userLng: Number(position.coords.longitude)})})}

We will now create a method that will get information from the Google directions API named “GetPolylineData”, we will also import “Axios” using the below command.

import Axios from ‘axios’;GetPolylineData = () =>{}

We will then use Axios to create a “GET” request to the API and start and finish our request string with backticks so we can use template literals and so our string looks neat, below is how the request starts (but it is not completely finished yet)

Axios.get(`https://maps.googleapis.com/maps/api/directions/json`)

We then need to use destructuring to access our state values like below (this just makes is easier to access our state and less code to write if we need to access the state multiple times)

GetPolylineData = () =>{const {userLat,userLng} = this.state;Axios.get(`https://maps.googleapis.com/maps/api/directions/json`)}

Next, you will need to set the origin query parameter of the url equal to the latitude and longitude of the users location, as this will be the origin of the request to get directions for. Next step is to then add another query parameter called “destination” which will be a latitude and longitude value (separated by commas ) of the place you wish to be the destination, mine is piccadilly circus so I will need to research the latitude and longitude value of this location. I have created 2 variables that will hold my lat and lng destination values just so my request string doesn’t get too long.

GetPolylineData = () =>{const {userLat,userLng} = this.state;const piccCircusLat = yourLatValueGoesHere;const pccCircusLng = yourLngValuesGoesHere;Axios.get(`https://maps.googleapis.com/maps/api/directions/json?origin=${userLat},${userLng}&destination=${piccCircusLat},${pccCircusLng}`)}

Above is how our request currently looks, just 2 more parameters and we are able to make a fully successful request.

A fantastic element of the Google directions API is that it can be highly customised, you can enter place ids as locations or enter as free text, specify routes to avoid as well as include a mode of transport, for this tutorial I will use walking as the mode of transport.

If you wish to know more, the documentation is here, it is very well laid out with examples and explanations.

Our next 2 parameters are the mode of transport and the API key.

After adding our “mode” parameter our request url looks like the below.

Axios.get(`https://maps.googleapis.com/maps/api/directions/json?origin=${userLat},${userLng}&destination=${piccCircusLat},${pccCircusLng}&mode=walking`)

We now need to import our API key from the file we created. Do this using the below command.

import {gapikey} from './keys';

Also, we now need to add this key to our request url using the mandatory “key” parameter, so now our full request looks like the below.

`https://maps.googleapis.com/maps/api/directions/json?origin=${userLat},${userLng}&destination=${piccCircusLat},${pccCircusLng}&mode=walking&key=${gapikey}`

We now need to run the method on our “componentDidMount” method.

componentDidMount() {Geolocation.getCurrentPosition(info => {this.setState({userLat: Number(info.coords.latitude),userLng: Number(info.coords.longitude)})this.GetPolylineData();})}

On your Axios call you will need to add a “then” and “catch” as they both return promises containing success data or error data.

Axios.get(`https://maps.googleapis.com/maps/api/directions/json?origin=${userLat},${userLng}&destination=${piccCircusLat},${pccCircusLng}&mode=walking&key=${gapikey}`).then(response => {console.log(response.data);}).catch(error=>{console.log('Error getting data: ' + error)})

You can see the output of your console by enabling debugging on your simulator. by pressing CMD and D on Mac and then clicking “Debug”, this will then open a tab on your browser which you can then use to see the output in the console in the developer tools.

Furthermore, we now need to install another package that will help us tremendously in decoding our polylines so they are usable to us, run the command below to install the package.

npm install @mapbox/polyline

This package will decode the polyline into lat lng array pairs. You can import it like so

import polyline from '@mapbox/polyline';

We will use the polyline method inside of our GetPolylineData method to decode the points returned from the API request. Use the code below to traverse through the object returned from the API and decode the points returned into latitude and longitude pairs.

let array = polyline.decode(response.data.routes[0].overview_polyline.points);

We then need to create another array containing objects and map over the contents of the “array” variable to do this, we set the latitude key equal to the first index of the value of the array, we access this value by using the “point” parameter which is equivalent to the current value being looped over by map.

let myCoords = array.map((point) => ({latitude: point[0],longitude: point[1]}));

We now need to create a new state value, call it something like “polylineCoords” and make the default value an array.

state = {userLat: 0.0,userLng: 0.0,polylineCoords: []}

We then need to set the state of “polylineCoords” equal to the array we just created.

this.setState({polylineCoords: myCoords});

We are very close to getting this working now, just a couple more steps, initially our MapView had no closing tag, we need to change this so it does as we will need the Polyline component (which we will import in a second) to be inside the MapView.

<MapViewinitialRegion={{latitude: 51.5123,longitude: -0.0910,latitudeDelta: 0.05,longitudeDelta: 0.05}}style={{ width: 400, height: 300 }}showsUserLocation></MapView>

So now your MapView should look like the above.

Next step is to also import the “Polyline” component from ‘react-native-maps’ like the below, this component will be used to show the polyline on the screen and will take in a “coordinates” property that will contain the array of objects that are the latitude and longitude points that we retrieved from the Google directions API.

import MapView,{Polyline} from 'react-native-maps';

You will now need to put your Polyline component in between the MapView start and end tags and set the coordinates property equal to the state value “polylineCoords”, I have also set a stroke colour and width but this is completely up to you how you want the polyline to show.

<Polylinecoordinates={this.state.polylineCoords} strokeWidth={3} strokeColor={'red'}/><MapViewinitialRegion={{latitude: 51.5123,longitude: -0.0910,latitudeDelta: 0.05,longitudeDelta: 0.05}}style={{ width: 400, height: 300 }}showsUserLocation><Polylinecoordinates={this.state.polylineCoords} strokeWidth={3} strokeColor={'red'}/></MapView>

And voila! Above is a screenshot of my iOS simulator after adding the polyline component.

I hope you have enjoyed and learned from this 2 part series, remember to share and give me a clap too haha!

See my blog here — https://simplyreact.uk/

--

--