Skip to content

Instantly share code, notes, and snippets.

@anilsomasundaran
Last active September 27, 2020 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anilsomasundaran/d88dbbc145120a4770c0bc5cc2c7dd40 to your computer and use it in GitHub Desktop.
Save anilsomasundaran/d88dbbc145120a4770c0bc5cc2c7dd40 to your computer and use it in GitHub Desktop.
CurrentLocation Component
<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>
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);
}
}
}
<?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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment