Newer Version Available
LocationService Example
Here’s a basic example of a Lightning web component that gets the user’s current
location and displays it on a map.
The HTML template provides the bare minimum for a location-based interface. There’s an element
to display the map, a bit of static help text, and a button to get the location. There are two
interesting aspects of this template:
- Disabling the Get Current Location button using the disabled attribute when not in a supported Salesforce mobile app. This attribute is set based on the results of isAvailable() when the component is initialized.
- A spinner that indicates “indeterminate progress” while waiting for the current location request to resolve.
1<!-- locationServiceExample.html -->
2<template>
3
4 <div class="slds-text-align_center">
5 <span class="slds-text-heading_large">Where in the World Am I?</span>
6 </div>
7
8 <!-- After the current location is received,
9 its value is displayed here: -->
10 <template lwc:if={currentLocation}>
11 <div class="slds-m-vertical_large slds-p-vertical_medium
12 slds-text-align_left slds-border_top slds-border_bottom">
13
14 <!-- Current location as latitude and longitude -->
15 Your current location is:
16 <pre>{currentLocationAsString}</pre>
17
18 <!-- Current location as a map -->
19 <lightning-map map-markers={currentLocationAsMarker} zoom-level=16>
20 </lightning-map>
21 </div>
22 </template>
23
24 <!-- While request is processing, show spinner -->
25 <div class="slds-m-around_large">
26 <template lwc:if={requestInProgress}>
27 <div class="slds-is-relative">
28 <lightning-spinner
29 alternative-text="Getting location...">
30 </lightning-spinner>
31 </div>
32 </template>
33 </div>
34
35 <!-- Static help text -->
36 <div class="slds-text-align_center slds-text-color_weak slds-m-vertical_large">
37 Click <strong>Get Current Location</strong> to see where you are.
38 </div>
39
40 <!-- The get-current-location button;
41 Disabled if LocationService isn't available -->
42 <div class="slds-align_absolute-center slds-m-vertical_large">
43 <lightning-button
44 variant="brand"
45 disabled={locationButtonDisabled}
46 icon-name="utility:target"
47 label="Get Current Location"
48 title="Use your device's GPS and other location sensors to determine your current location"
49 onclick={handleGetCurrentLocationClick}>
50 </lightning-button>
51 </div>
52</template>Once the current location is determined, we use the lightning-map base component to display it. Each phase of the location request lifecycle writes a console message.
1// locationServiceExample.js
2import { LightningElement } from 'lwc';
3import { ShowToastEvent } from 'lightning/platformShowToastEvent';
4import { getLocationService } from 'lightning/mobileCapabilities';
5
6export default class LocationServiceExample extends LightningElement {
7
8 // Internal component state
9 myLocationService;
10 currentLocation;
11 locationButtonDisabled = false;
12 requestInProgress = false;
13
14 // When component is initialized, detect whether to enable Location button
15 connectedCallback() {
16 this.myLocationService = getLocationService();
17 if (this.myLocationService == null || !this.myLocationService.isAvailable()) {
18 this.locationButtonDisabled = true;
19 }
20 }
21
22 handleGetCurrentLocationClick(event) {
23 // Reset current location
24 this.currentLocation = null;
25
26 if(this.myLocationService != null && this.myLocationService.isAvailable()) {
27
28 // Configure options for location request
29 const locationOptions = {
30 enableHighAccuracy: true
31 }
32
33 // Show an "indeterminate progress" spinner before we start the request
34 this.requestInProgress = true;
35
36 // Make the request
37 // Uses anonymous function to handle results or errors
38 this.myLocationService
39 .getCurrentPosition(locationOptions)
40 .then((result) => {
41 this.currentLocation = result;
42
43 // result is a Location object
44 console.log(JSON.stringify(result));
45
46 this.dispatchEvent(
47 new ShowToastEvent({
48 title: 'Location Detected',
49 message: 'Location determined successfully.',
50 variant: 'success'
51 })
52 );
53 })
54 .catch((error) => {
55 // Handle errors here
56 console.error(error);
57
58 // Inform the user we ran into something unexpected
59 this.dispatchEvent(
60 new ShowToastEvent({
61 title: 'LocationService Error',
62 message:
63 'There was a problem locating you: ' +
64 JSON.stringify(error) +
65 ' Please try again.',
66 variant: 'error',
67 mode: 'sticky'
68 })
69 );
70 })
71 .finally(() => {
72 console.log('#finally');
73 // Remove the spinner
74 this.requestInProgress = false;
75 });
76 } else {
77 // LocationService is not available
78 // Not running on hardware with GPS, or some other context issue
79 console.log('Get Location button should be disabled and unclickable. ');
80 console.log('Somehow it got clicked: ');
81 console.log(event);
82
83 // Let user know they need to use a mobile phone with a GPS
84 this.dispatchEvent(
85 new ShowToastEvent({
86 title: 'LocationService Is Not Available',
87 message: 'Try again from the Salesforce app on a mobile device.',
88 variant: 'error'
89 })
90 );
91 }
92 }
93
94 // Format LocationService result Location object as a simple string
95 get currentLocationAsString() {
96 return `Lat: ${this.currentLocation.coords.latitude}, Long: ${this.currentLocation.coords.longitude}`;
97 }
98
99 // Format Location object for use with lightning-map base component
100 get currentLocationAsMarker() {
101 return [{
102 location: {
103 Latitude: this.currentLocation.coords.latitude,
104 Longitude: this.currentLocation.coords.longitude
105 },
106 title: 'My Location'
107 }]
108 }
109}