Chapter 6. Working with Geolocation and Maps

So far you've seen that React Native simplifies the creation of native UI components, such as lists, text fields, and buttons, and it gives you simple abstractions, such as AsyncStorage, to work with underlying native APIs. Soon, you'll see that you also have access to advanced components, such as maps using the MapView component, and that you can access more advanced native features, such as geolocation using React Native's Geolocation API. We'll demonstrate these capabilities by adding the ability to capture and save current GPS coordinates with each new note. Note that the next two chapters will focus on iOS development, as the feature set for Android is not complete.

In this chapter we will cover the following topics:

  • Learning how to get the current geolocation
  • Listening for changes to the user's position
  • Ensuring that our app requires appropriate permissions
  • Saving location data with each note
  • Displaying the original locations of all the notes on a MapView

Let's get started!

Introducing the Geolocation API

React Native provides an easy-to-use abstraction over the native Geolocation APIs. It follows the MDN (Mozilla Developer Network) specification, which recommends the following geolocation interface:

navigator.geolocation.getCurrentPosition(success, error, options)

This method asynchronously asks for the device's current location and will call the success callback with a Position object if it is successful and the error callback if it fails (usually, due to misconfigured permissions in your app or the user explicitly rejecting the request to allow your app to know their location). The options argument allows you to request higher position accuracy, define how long you're willing to wait for a response, and specify the maximum age of cached data that you're willing to accept:

navigator.geolocation.watchPosition(success, error, options)

This function enables you to register a function that will be called each time the position changes. This function returns an integer that represents the id of the callback you registered. This allows you to stop listening for updates by calling the following:

navigator.geolocation.clearWatch(id);

The location permission in iOS

Before we begin integrating geolocation into our notes, we need to configure a permission to request the user's location. From Xcode, open info.plist and make sure that the NSLocationWhenInUseUsageDescription key is located in the file (it should be enabled by default):

The location permission in iOS

Once the application starts up, you should see a permission modal automatically pop up in the center of the screen:

The location permission in iOS
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.156