7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial

Next lesson playing in 5 seconds

Cancel
  • Overview
  • Transcript

2.7 Geolocation API

There are certain pieces of a mobile application that can’t be described as a component. For this, React Native has APIs that offer access to important features. In this lesson, we're going to integrate the Geolocation API into our course project.

2.7 Geolocation API

Hi and welcome back to Get Started with React Native. In this lesson, we will have a look at React Native APIs, especially the Geolocation API. APIs in React Native provide access to features that are not necessarily components, but are important to platform features. An example will be an alert that gets displayed on the screen, or the possibility to make the device vibrate. Some API's are platform specific and have the suffix iOS or Android in the name. Before we have a look at the geolocation API, let's look at some other useful APIs. First up, NetInfo. It fetches the current connectivity status of the device and displays the type of connection it currently has. On iOS, it is limited to none, cell, and wifi. But on Androids you can get a big variety of additional types, like ethernet, Bluetooth, or VPN. If the quality changes, an event will be triggered, and you can change your user interface accordingly. The second API that you might want to use in your app is AsyncStorage. It provides simple and persistent key-value store. AsyncStorage allows you to set, get, and remove items from the store by using a key. If you're storing JSON, you can also merge values together. All those functions are also available to handle multiple keys at once, very handy. But now let's switch to the Geolocation API, which will be part of our course project. This API is very simple. It only has four functions: getCurrentPosition, watchPosition, clearWatch and stopObserving. The first three functions are also part of the Geolocation API you can use in your browser. To use the user's location, you have to add the NSLocationWhenInUseUsageDescription key to Info.plist, which is automatically done for you during React Native in it. If you want to use the location in the background, you have to add this to your capabilities and include the NSLocationAlwaysUsageDescription key. Normally this keys should contain a description why do you have once a location. On Android, you need to add the users permission to ACCESS_FINE_LOCATION to your AndroidManifest.xml. To continuously watch the location for updates, you use watchPosition and add a callback to it. You can also add a timeout, enableHighAccuracy or only receive significant updates by adding distance filter. If you are done watching, use clearWatch for the observer instead of stopObserving because this will stop it at wide. Okay, it's implementation time. Geolocation doesn't need to be imported. It can be used through the navigator.geolocation polyfill. In the constructor I'm going to add a call to watchPosition on the geolocation object, which receives a callback with a position. Here I'm going to use the same logic that we had last lesson. Enter the marker with the coordinates and the key. I'm also going to add a distanceFilter of 10 meters so we don't get too many updates. I also want to watchID from the listener, so I can set it to the state. It's not important here since we are dealing with the route component. But I wanted to show you how it's done. Let's add another method called componentWillUnmount. It will get a call to geolocation.stopWatch and get passed to start.watchID. This will delete the listener when the component gets removed from the DOM. With that in place as a first step let's remove the followsUserLocation and onRegionChange from the last lesson and try it out. It already works with markers. Now let's change it to draw a line. To do this we need to swap out the marker with the PolyLine component. It takes an array of coordinates, which we can build by using map on the markers and return the coordinate for each. Let's also add a thicker line. Here you go, the line is drawn successfully. Now it's time to get the distance, speed and direction. I'm going to start with speed since it's the easiest. It's available directly from the position attribute as position.coords.speed. Let's set that to the value of speedInfo. The direction is also available directly but as a heading number, not a bearing. I'm going to paste in the code for this since it's quite tedious to write. Here you go, if the position.coords.heading value is between one of those values, it shows the correct bearing. Now, calculating the distance is a different story. When you want to do it correctly, you have to use the haversine formula. Luckily there is a JavaScript module that does exactly that. We can easily install it with yarn. And then restart the packager. To use it, just import haversine at the top. To make the calculation easier, I'm going to calculate the distance based on the previous coordinates, and store the results in the component state. Using the haversine function with the previous and current coordinates, we can do the calculation and add it to the previous value. Haversine defaults to kilometers. But you can also change it to meters or miles. Great, now we have a working tracking app that also shows distance traveled, current speed, and direction. To recap, React Native APIs allow access to platform features that aren't components. Platform specific APIs have the iOS or Android suffix in the name. NetInfo and AsyncStorage are two important APIs you should be aware of. Geolocation can continuously inform you about updates but watch precision. It can be used through navigator.geolocation. In the next lesson, we are going to look at Redux and how to store application state with it. See you there.

Back to the top