User’s Current Geolocation Component in LWC

In this blog, I would like to share with you a custom component which can be able to locate your geolocation on the google map. This component is developed using the lightning:map base component and navigator api in browser window object.

Html template is simple and it only contains a map component surrounded by a lightning card. The Geolocation API allows the user to provide their location to web applications and it can be accessed via a call to navigator.geolocation. Browser’s geolocation is accessed in the renderedcallback method as the location should be captured before on the component rendering phase.

getCurrentPosition() method in the Geolocation API is used to get the current position of the device by providing options along with success and error callback.

navigator.geolocation.getCurrentPosition(<success callback> , <error callback>, [options])

Option is an optional object of PositionOptions objects which includes below parameters

  • maximumAge: integer (milliseconds) | infinity – maximum cached position age.
  • timeout: integer (milliseconds) – amount of time before the error callback is invoked, if 0 it will never invoke.
  • enableHighAccuracy: false | true

Sample option parameter passed to navigator api is given below and make necessary modification as per your requirement.

options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};
<template>
<lightning-card variant="Narrow" title="Current Location" icon-name="standard:account">
<p class="slds-p-horizontal_small">
<lightning-map map-markers={mapMarkers} zoom-level="10"></lightning-map>
</p>
</lightning-card>
</template>
view raw currentLocation.html hosted with ❤ by GitHub
import { LightningElement, track } from 'lwc';
export default class CurrentLocation extends LightningElement {
//stores current latitude and longitude for map component
mapMarkers=[];
//flag restricts accessing geolocation api multiple times
isRendered = false;
//callback after the component renders
renderedCallback() {
console.log('>>> in rendered callback');
if(!this.isRendered){
this.getCurrentBrowserLocation();
}
//sets true once the location is fetched
this.isRendered = true;
}
getCurrentBrowserLocation() {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
if(navigator.geolocation) {
//accessing getCurrentPosition method
navigator.geolocation.getCurrentPosition((position)=> {
//success callback
console.log('>>>positions' + position);
let currentLocation = {
location : {
Latitude: position.coords.latitude,
Longitude: position.coords.longitude
},
title : 'My location'
};
this.mapMarkers = [currentLocation];
}, (error) => {
//error callback
}, options);
}
}
}
view raw currentLocation.js hosted with ❤ by GitHub
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>49.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Also, we have used a isRendered flag which will helps to restrict to access the location api multiple times otherwise browser will be blocked and restricts other components from rendering on the browser.

Please go through below link for more details

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API

Leave a Reply

%d bloggers like this: