Sometimes an app may require a user’s current location properties, such as latitude and longitude, in order to enable location-related functionalities.
Location properties allow you to access a current user’s geolocation, or location at a given moment, and provide specific services based on their particular area.
With geolocation, you can access user details including:
In this guide, you'll learn to show and update a user's geolocation on a map.
You can access a user's geolocation using the JavaScript API navigator.geolocation
, which allows you to ask for location permission. If the user gives permission, location properties can be accessed.
There are two methods available to get the location of the user.:
The first step is finding out if a user's geolocation is available or not.
1componentDidMount() {
2 if ("geolocation" in navigator) {
3 console.log("Available");
4 } else {
5 console.log("Not Available");
6 }
7 }
If the code above returns true
, then you can access various geolocation properties. If not, then the user has disabled the location access.
Get the current position of the user using the navigator.getCurrentPosition()
method.
1import React, { Component } from "react";
2import { render } from "react-dom";
3
4class App extends Component {
5 constructor(props) {
6 super(props);
7 this.state = {
8 };
9 }
10
11 componentDidMount() {
12 navigator.geolocation.getCurrentPosition(function(position) {
13 console.log("Latitude is :", position.coords.latitude);
14 console.log("Longitude is :", position.coords.longitude);
15 });
16 }
17
18 render() {
19 return (
20 <div>
21 <h4>Using geolocation JavaScript API in React</h4>
22 </div>
23 );
24 }
25}
26
27render(<App />, document.getElementById("root"));
Open the console, and the output should look like this.
1Latitude is : xx.xxxxxx
2Longitude is : xx.xxxxxx
The xxx can be any number based on the location.
Try the following code to get the complete position of the user.
1componentDidMount() {
2 navigator.geolocation.getCurrentPosition(function(position) {
3 console.log(position)
4 });
5 }
The output in the console will look like this.
1GeolocationPosition {
2 coords: GeolocationCoordinates,
3 timestamp: 1583849180132
4 }
5 coords: {
6 GeolocationCoordinateslatitude: 19.xxxxxxx
7 longitude: 73.xxxxxx
8 altitude:
9 nullaccuracy: 1158
10 altitudeAccuracy: null
11 heading: null
12 speed: null
13 __proto__: GeolocationCoordinates
14 timestamp: 1583849180132
15 }
16__proto__: GeolocationPosition
getCurrentPosition
returns the success object as a position property, but along with the success callback, you also have the error callback. It can be implemented with the following code.
1componentDidMount() {
2 navigator.geolocation.getCurrentPosition(
3 function(position) {
4 console.log(position);
5 },
6 function(error) {
7 console.error("Error Code = " + error.code + " - " + error.message);
8 }
9 );
10 }
Error callback is used to get the error related to position such as disallow the location and so on. When you open the console and disallow the location,you will get an error that looks like this.
Error Code = 1 - Geolocation has been disabled in this document by Feature Policy
getCurrentPosition
, allows you to access the current position, but what if the user changes their location? watchPosition
attaches the handler function and executes itself as soon as the user changes their current location, returning the updated location properties for the user's new position.
The following code will get the basic location properties.
1import React, { Component } from "react";
2import { render } from "react-dom";
3
4class App extends Component {
5 constructor(props) {
6 super(props);
7 this.state = {};
8 }
9
10 componentDidMount() {
11 if (navigator.geolocation) {
12 navigator.geolocation.watchPosition(function(position) {
13 console.log("Latitude is :", position.coords.latitude);
14 console.log("Longitude is :", position.coords.longitude);
15 });
16 }
17 }
18
19 render() {
20 return (
21 <div>
22 <h4>Using geolocation JavaScript API in React</h4>
23 </div>
24 );
25 }
26}
27
28render(<App />, document.getElementById("root"));
Open the console, and you will see that the new position properties are updated as soon as user changes their location.
Maps are a primary way to show a user’s current position. You'll need some location parameters, such as latitude and longitude, to render the current location.
Note: Before using a map, you should have a Google Map API key. Otherwise, the map will not work and will show an error.
Install this map library, which will allow you to get started with a map quickly.
1npm install google-maps-react
Using this library, you can pass the location data, and based on that data, the specific location of the user will be highlighted on the map.
Open the new component and write the following code snippet.
1import React, { Component } from "react";
2import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';
3
4const mapStyles = {
5 width: '100%',
6 height: '100%'
7};
8
9class Demo1 extends Component {
10 constructor() {
11 super();
12 this.state = {
13 name: "React"
14 };
15 }
16
17 render() {
18 return (
19 <div>
20 <Map
21 google={this.props.google}
22 zoom={14}
23 style={mapStyles}
24 initialCenter={{
25 lat: YOUR_LATITUDE,
26 lng: YOUR_LONGITUDE
27 }}
28 >
29 <Marker
30 onClick={this.onMarkerClick}
31 name={'This is test name'}
32 />
33 </Map>
34 </div>
35 );
36 }
37}
38
39export default GoogleApiWrapper({
40 apiKey: 'API_KEY'
41})(Demo1);
Note: You'll need to replace your google maps API key with API_KEY
. Otherwise, the map won’t be able to render the location-related properties.
Based on the latitude and longitude, a map will be able to load the exact location. The location will be identified as a marker on the map.
JavaScript provides a number of other interfaces that work closely with location properties based on different functional requirements.
In this guide, you learned how to use JavaScript’s Geolocation APIs to work with user locations and related properties. You can try out all the inbuilt APIs that allow you to read user locations and process them accordingly. If you have any queries, feel free to reach out at Codealphabet.