Geolocation in Lightning Web Components (LWC)

 1. Create a Lightning Web Component

You’ll need two files: geolocation.js for your JavaScript logic and geolocation.html for the template.

geolocation.js

import { LightningElement, track } from 'lwc'; export default class GeolocationExample extends LightningElement { @track latitude; @track longitude; @track error; connectedCallback() { this.getLocation(); } getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( position => { this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; }, error => { this.error = this.getErrorMessage(error); } ); } else { this.error = 'Geolocation is not supported by this browser.'; } } getErrorMessage(error) { switch (error.code) { case error.PERMISSION_DENIED: return 'User denied the request for Geolocation.'; case error.POSITION_UNAVAILABLE: return 'Location information is unavailable.'; case error.TIMEOUT: return 'The request to get user location timed out.'; case error.UNKNOWN_ERROR: return 'An unknown error occurred.'; } } }

2. Create the HTML Template

geolocation.html

<template> <lightning-card title="Geolocation Example"> <div class="slds-p-around_medium"> <template if:true={latitude}> <p>Latitude: {latitude}</p> <p>Longitude: {longitude}</p> </template> <template if:true={error}> <p class="slds-text-color_error">{error}</p> </template> </div> </lightning-card> </template>


Comments

Popular posts from this blog

How to Get a Salesforce Access Token from LWC Using Client Credentials Flow

Custom Round Robin Assignment with Apex and Custom Settings: A Comprehensive Guide