Updated April 20, 2023
Introduction of React Native Geolocation
The Geolocation API is needed for fetching the latitude and longitude of a geographical location. The Geolocation web specifications are extended by Geolocation API. We don’t have to import the Geolocation API as the Geolocation API is already available in navigator.geolocation global. Android.location API is used by Geolocation API on the Android Platform. As the accuracy of this API is less and the Google Location Services API is faster than this, Google does not recommend this API. In React Native, if we want to use Google Location Services API then we can use react native geolocation service module.
Syntax:
The syntax used to fetch the current location of the user with accuracy is mentioned below:
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
console.log(error.code, error.message);
},
{ enableHighAccuracy:
true, timeout:
15000,maximumAge:
10000 }
);
Working of React Native Geolocation with Examples
There are different methods returned by Geolocation API like getCurrentPosition, watchPosition which are available as polyfill in React Native. The getCurrentPosition API is used for getting the current location of the device and the watchPosition is used to subscribe for location updates of a device. The Geolocation API can be accessed easily using navigator.geolocation and there is no need to import it. In React Native Geolocation API is a global navigator object just like it is on web.
1. Your Current Location Tracer
In the example below, user’s current location is fetched using fetchingPositionandgetCurrentPosition. The pop-up comes on the window with demanding an access to user’s current location. When access is granted, the current location of the user is fetched and latitude and longitude of the location gets displayed in the output window. If the user don’t provide access of his/her location, then in the output window, text appears as “User denied Geolocation” above blank latitude and longitude value.
The files used to implement the code below are:
Content.js
import React from "react";
import PropTypes from "prop-types";
export default class Geolocation extends React.Component {
constructor(props) {
super(props);
this.state = {
fetchingPosition: false,
position: undefined,
error: undefined
};
}
componentWillMount() {
if (typeofwindow !== "object") {
return;
}
if (!("geolocation" in window.navigator)) {
return;
}
if (this.props.lazy) {
return;
}
this.getCurrentPosition();
}
componentWillUnmount() {
this.willUnmount = true;
}
getCurrentPosition = () => {
const {
enableHighAccuracy,
timeout,
maximumAge,
onSuccess,
onError
} = this.props;
this.setState({ fetchingPosition: true });
return window.navigator.geolocation.getCurrentPosition(
position => {
if (this.willUnmount) return;
this.setState({ position, fetchingPosition: false }, () =>
onSuccess(position)
);
},
error => {
if (this.willUnmount) return;
this.setState({ error, fetchingPosition: false }, () =>onError(error));
},
{ enableHighAccuracy, timeout, maximumAge }
);
};
render() {
if (!this.props.render) {
return null;
}
return (
this.props.render({
getCurrentPosition: this.getCurrentPosition,
fetchingPosition: this.state.fetchingPosition,
position: this.state.position,
error: this.state.error
}) || null
);
}
}
Geolocation.propTypes = {
enableHighAccuracy: PropTypes.bool,
timeout: PropTypes.number,
maximumAge: PropTypes.number,
onSuccess: PropTypes.func,
onError: PropTypes.func,
lazy: PropTypes.bool
};
Geolocation.defaultProps = {
enableHighAccuracy: false,
timeout: Infinity,
maximumAge: 0,
onSuccess: pos => {},
onError: err => {},
lazy: false
};
index.js
import React from "react";
import ReactDOM from "react-dom";
import Geolocation from "./Content";
import "./styles.css";
class App extends React.Component {
getCurrentPosition = () => {
const geolocation = navigator.geolocation;
geolocation.getCurrentPosition(
position => {
console.log(position);
},
() => {
console.log(new Error("Permission denied"));
}
);
};
render() {
return (
<div className="App">
<h1>Heyoo Welcome To Location Tracer</h1>
<h2>We are keeping an EYE on you!</h2>
<Geolocation
render={({
fetchingPosition,
position: { coords: { latitude, longitude } = {} } = {},
error,
getCurrentPosition
}) => (
<div>
<button onClick={getCurrentPosition}>Click For Your Position</button>
<br />
<br />
{error &&<div>{error.message}</div>}
<pre>
longitude of your location: {longitude}
<br />
<br />
latitude of your location: {latitude}
<br />
.........
<br />
.........
<br />
<h3>Yeah! We are Right, so beware of us.</h3>
</pre>
</div>
)}
/>
</div>
);
}
}
constrootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
styles.css
.App {
font-family: 'Times New Roman'
, Times
, serif;
text-align: center;
background-color: #de3761;
border-bottom-color: #4997f5;
}
Output:
The below output comes when you provide the access to your location.
The below output comes when you don’t provide the access to your location.
2. On React Google maps
In the example below, user’s current location is fetched and displayed on the Google Maps along with latitude and longitude of the location.
index.html
<div id="root"></div>
index.js
import React from "react";
import ReactDOM from "react-dom";
import { compose
, withProps } from "recompose";
import {
withScriptjs
, withGoogleMap
, GoogleMap
, Marker
} from "react-google-maps";
class MyMap extends React.Component {
constructor(props) {
super(props);
this.state = {
lat: 0,
lng: 0,
};
}
componentWillMount(){
if (!!navigator.geolocation) {
navigator.geolocation.watchPosition((position) => {
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
},
(err) => console.log(err),
{ enableHighAccuracy:
true, timeout:
10000, maximumAge:
10000 },
);
} else {
alert('Access not Granted,')
}
}
render() {
const { p } = this.props;
const { lat
, lng } = this.state;
console.log(lat, lng)
return (
<div>
<GoogleMap
ref={map => {
this.map = map;
if (map &&lat&&lng) {
console.log(bounds);
const bounds = new google.maps.LatLngBounds({ lat, lng });
map.panTo({ lat, lng });
}
}}
zoom={18}
defaultCenter={{ lat, lng }}
>
{p.isMarkerShown&& (
<Marker position={{ lat, lng }} />
)}
</GoogleMap>
{lat} <br />
{lng}
</div>
);
}
}
constMyMapComponent = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyDNjpHU_Fxjkx7q2mjCfoA2zU2f7EXTWoI&v&v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `99%` }} />,
containerElement: <div style={{ height: `350px` }} />,
mapElement: <div style={{ height: `99%` }} />
}),
withScriptjs,
withGoogleMap
)(props =><MyMap p={props} />);
ReactDOM.render(<MyMapComponentisMarkerShown />, document.getElementById("root"));
Output:
Conclusion
On the basis of the above article, we can understand the concept of React Native Geolocation and it working. The examples described above help us in understanding the application of Geolocation according to the different requirements of the website. I hope this article would have made the concept simpler to understand and work upon.
Recommended Articles
This is a guide to React Native Geolocation. Here we also discuss the introduction, syntax and working of react native geolocation along with different examples and its code implementation. You may also have a look at the following articles to learn more –