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