Where am I?

The geolocation API that web applications use to figure out where the user is located can also be used by React Native applications because the same API has been polyfilled. Outside of maps, this API is useful for getting precise coordinates from the GPS on mobile devices. You can then use this information to display meaningful location data to the user.

Unfortunately, the data that's returned by the geolocation API is of little use on its own; your code has to do the legwork to transform it into something useful. For example, latitude and longitude don't mean anything to the user, but you can use this data to look up something that is of use to the user. This might be as simple as displaying where the user is currently located.

Let's implement an example that uses the geolocation API of React Native to look up coordinates and then use those coordinates to look up human-readable location information from the Google Maps API:

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { fromJS } from 'immutable';

import styles from './styles';

// For fetching human-readable address info.
const URL = 'https://maps.google.com/maps/api/geocode/json?latlng=';

export default class WhereAmI extends Component {
// The "address" state is "loading..." initially because
// it takes the longest to fetch.
state = {
data: fromJS({
address: 'loading...'
})
};

// Getter for "Immutable.js" state data...
get data() {
return this.state.data;
}

// Setter for "Immutable.js" state data...
set data(data) {
this.setState({ data });
}

// We don't setup any geo data till the component
// mounts.
componentDidMount() {
const setPosition = pos => {
// This component renders the "coords" data from
// a geolocation response. This can simply be merged
// into the state map.
this.data = this.data.merge(pos.coords);

// We need the "latitude" and the "longitude"
// in order to lookup the "address" from the
// Google maps API.
const {
coords: { latitude, longitude }
} = pos;

// Fetches data from the Google Maps API then sets
// the "address" state based on the response.
fetch(`${URL}${latitude},${longitude}`)
.then(resp => resp.json(), e => console.error(e))
.then(({ results: [{ formatted_address }] }) => {
this.data = this.data.set('address', formatted_address);
});
};

// First, we try to lookup the current position
// data and update the component state.
navigator.geolocation.getCurrentPosition(setPosition);

// Then, we setup a high accuracy watcher, that
// issues a callback whenever the position changes.
this.watcher = navigator.geolocation.watchPosition(
setPosition,
err => console.error(err),
{ enableHighAccuracy: true }
);
}

// It's always a good idea to make sure that this
// "watcher" is cleared when the component is removed.
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watcher);
}

render() {
// Since we want to iterate over the properties
// in the state map, we need to convert the map
// to pairs using "entries()". Then we need to
// use the spread operator to make the map iterator
// into a plain array. The "sort()" method simply
// sorts the map based on it's keys.
const state = [...this.data.sortBy((v, k) => k).entries()];

// Iterates over the state properties and renders them.
return (
<View style={styles.container}>
{state.map(([k, v]) => (
<Text key={k} style={styles.label}>
{`${k[0].toUpperCase()}${k.slice(1)}`}: {v}
</Text>
))}
</View>
);
}
}

The goal of this component is to render the properties returned by the geolocation API on the screen, as well as look up the user's specific location, and display it. If you take a look at the componentDidMount() method, you'll see that this is where most of the interesting code is. The setPosition() function is used as a callback in a couple of places. Its job is to set the state of your component.

First, it sets the coords properties. Normally, you wouldn't display this data directly, but this is an example that's showing the data that's available as part of the geolocation API. Second, it uses the latitude and longitude values to look up the name of where the user is currently, using the Google Maps API.

The setPosition() callback is used with getCurrentPosition(), which is only called once when the component is mounted. You're also using setPosition() with watchPosition(), which calls the callback any time the user's position changes.

The iOS emulator and Android Studio let you change locations via menu options. You don't have to install your app on a physical device every time you want to test changing locations.

Let's see what this screen looks like once the location data has loaded:

The address information that was fetched is probably more useful in an application than latitude and longitude data. Even better than physical address text is visualizing the user's physical location on a map; you'll learn how to do this in the next section.

..................Content has been hidden....................

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