In this challenge, we’ll explore the use of a handy API for mobile apps (geolocation) to enhance the app you made in Challenge 5.
Building on top of what you already made in Challenge 5, enhance your venue list by showing in real-time how far away the user is from each venue.
In addition to location-oriented components like <MapView>
, React Native provides a Geolocation API to the spec of https://developer.mozilla.org/en-US/docs/Web/API/Geolocation. This API lets you do perform more advanced, non-map based activity based on location.
Using this API, you can get a user’s current position (getCurrentPosition
), subscribe to updates of the user’s position (watchPosition
), and clear the aforementioned subscription (clearWatch
).
Geolocation functions are available through the navigator.geolocation
global, so you don’t need to import anything.
A simple example:
// ...
componentDidMount() {
const positionOptions = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 1000
}
const onSuccess = (position) => {
// on successful retrieval of a position, this function will execute
this.setState({ position })
}
const onFailure = (error) => {
// on a failed attempt to get a position, this function will execute
alert(error)
}
navigator.geolocation.getCurrentPosition(onSuccess, onFailure, positionOptions)
}
// ...
Hit the docs for more details, and examples of the API in use.
Feel free to use the below function to calculate the distance between two lat/longs in miles.
function distance(lat1, lon1, lat2, lon2) {
var φ1 = Math.PI * lat1 / 180;
var φ2 = Math.PI * lat2 / 180;
var theta = lon1 - lon2;
var radtheta = Math.PI * theta / 180;
var dist =
Math.sin(φ1) * Math.sin(φ2) +
Math.cos(φ1) * Math.cos(φ2) * Math.cos(radtheta);
dist = Math.acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515;
return dist.toFixed(2);
}
If you’re using the iOS simulator (and not the Expo app) the simulator may not provide a location to your app by default. To change this, click the “Debug” item in the Simulator menubar, hover over “Location” at the bottom, and select “Freeway Drive”. This sets up the simulator to simulate the location of somebody cruising the freeway through the bay area. (You might need to restart your simulator for this setting to take effect.)
Add real-time distances to your venue list. For bonus points,
When you’re done, post a screenshot in the #progress channel. That’s it. You’re done!