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

See Also