Introduction :
In the realm of Salesforce development, the Lightning Web Component (LWC) framework has become the go-to choice for building dynamic and responsive user interfaces within the Salesforce ecosystem. Lightning Web Component (LWC) framework, offers developers a robust Location Service API, empowering them to integrate powerful geolocation features seamlessly into their applications. In this blog post, we’ll delve into Lightning Web Component Location Service API, exploring its capabilities and demonstrating how to leverage its potential to create compelling location-aware applications.
What is Location Service API ?
The Location Service API is a part of the Lightning Web Components framework provided by Salesforce. A Lightning web component can use a mobile device’s location features to determine the current location of the device. You can access the device’s current location at a moment in time, or you can subscribe to location changes, and receive updates to the device’s location when it changes significantly.
With the Location Service API, developers can retrieve latitude, longitude, altitude, accuracy, and other location-related information. It doesn’t include derived data, such as a physical address or map detail. Here are few location-based features where Location Service API might be useful.
- Geolocation : Point user’s location on map.
- Geofencing : Trigger notification when user’s enter or exist predefined geographical boundaries.
- Route Planning : Provide direction for travel between two points.
Getting Started :
Integrating the Location Service API into your Lightning web components is straightforward. Here’s a step-by-step guide:
- Import the API : import
import { getLocationService } from 'lightning/mobileCapabilities';
in your component javascript file. - Check availability : Ensure the API is available before using it with
getLocationService().isAvailable()
- Get Current Location : Get current location
getLocationService().getCurrentPosition({ enableHighAccuracy: true })
Location Service API Example :
<!-- locationServiceCmp.html -->
<template>
<div class="slds-text-align_center">
<span class="slds-text-heading_large">Where in the World Am I?</span>
</div>
<!-- After the current location is received,
its value is displayed here: -->
<template lwc:if={currentLocation}>
<div class="slds-m-vertical_large slds-p-vertical_medium
slds-text-align_left slds-border_top slds-border_bottom">
<!-- Current location as latitude and longitude -->
Your current location is:
<pre>{currentLocationAsString}</pre>
<!-- Current location as a map -->
<lightning-map map-markers={currentLocationAsMarker} zoom-level=16>
</lightning-map>
</div>
</template>
<!-- While request is processing, show spinner -->
<div class="slds-m-around_large">
<template lwc:if={requestInProgress}>
<div class="slds-is-relative">
<lightning-spinner
alternative-text="Getting location...">
</lightning-spinner>
</div>
</template>
</div>
<!-- Static help text -->
<div class="slds-text-align_center slds-text-color_weak slds-m-vertical_large">
Click <strong>Get Current Location</strong> to see where you are.
</div>
<!-- The get-current-location button;
Disabled if LocationService isn't available -->
<div class="slds-align_absolute-center slds-m-vertical_large">
<lightning-button
variant="brand"
disabled={locationButtonDisabled}
icon-name="utility:target"
label="Get Current Location"
title="Use your device's GPS and other location sensors to determine your current location"
onclick={handleGetCurrentLocationClick}>
</lightning-button>
</div>
</template>
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getLocationService } from 'lightning/mobileCapabilities';
export default class LocationServiceCmp extends LightningElement {
// Internal component state
myLocationService;
currentLocation;
locationButtonDisabled = false;
requestInProgress = false;
// When component is initialized, detect whether to enable Location button
connectedCallback() {
this.myLocationService = getLocationService();
if (this.myLocationService == null || !this.myLocationService.isAvailable()) {
this.locationButtonDisabled = true;
}
}
handleGetCurrentLocationClick(event) {
// Reset current location
this.currentLocation = null;
if(this.myLocationService != null && this.myLocationService.isAvailable()) {
// Configure options for location request
const locationOptions = {
enableHighAccuracy: true
}
// Show an "indeterminate progress" spinner before we start the request
this.requestInProgress = true;
// Make the request
// Uses anonymous function to handle results or errors
this.myLocationService
.getCurrentPosition(locationOptions)
.then((result) => {
this.currentLocation = result;
// result is a Location object
console.log(JSON.stringify(result));
this.dispatchEvent(
new ShowToastEvent({
title: 'Location Detected',
message: 'Location determined successfully.',
variant: 'success'
})
);
})
.catch((error) => {
// Handle errors here
console.error(error);
// Inform the user we ran into something unexpected
this.dispatchEvent(
new ShowToastEvent({
title: 'LocationService Error',
message:
'There was a problem locating you: ' +
JSON.stringify(error) +
' Please try again.',
variant: 'error',
mode: 'sticky'
})
);
})
.finally(() => {
console.log('#finally');
// Remove the spinner
this.requestInProgress = false;
});
} else {
// LocationService is not available
// Not running on hardware with GPS, or some other context issue
console.log('Get Location button should be disabled and unclickable. ');
console.log('Somehow it got clicked: ');
console.log(event);
// Let user know they need to use a mobile phone with a GPS
this.dispatchEvent(
new ShowToastEvent({
title: 'LocationService Is Not Available',
message: 'Try again from the Salesforce app on a mobile device.',
variant: 'error'
})
);
}
}
// Format LocationService result Location object as a simple string
get currentLocationAsString() {
return `Lat: ${this.currentLocation.coords.latitude}, Long: ${this.currentLocation.coords.longitude}`;
}
// Format Location object for use with lightning-map base component
get currentLocationAsMarker() {
return [{
location: {
Latitude: this.currentLocation.coords.latitude,
Longitude: this.currentLocation.coords.longitude
},
title: 'My Location'
}]
}
}
Considerations and Limitations :
- Location Service API is accessible when it runs within a compatible Salesforce mobile app.
- Salesforce Mobile app
- Mobile Publisher for Salesforce App
- Mobile Publisher for Experience Cloud
- Field Service Mobile app
References :
- https://developer.salesforce.com/docs/atlas.en-us.mobile_offline.meta/mobile_offline/use_locationservice.htm
- https://developer.salesforce.com/docs/platform/lwc/guide/reference-lightning-locationservice.html