본문 바로가기

개발자정보

Salesforce(세일즈포스) Current Geolocation Component

반응형

In this blog, I would like to share with you a custom component which can be able to locate your geolocation on the google map. This component is developed using the lightning:map base component and navigator api in browser window object.

Html template is simple and it only contains a map component surrounded by a lightning card. The Geolocation API allows the user to provide their location to web applications and it can be accessed via a call to navigator.geolocation. Browser’s geolocation is accessed in the renderedcallback method as the location should be captured before on the component rendering phase.

getCurrentPosition() method in the Geolocation API is used to get the current position of the device by providing options along with success and error callback.

navigator.geolocation.getCurrentPosition(<success callback> , <error callback>, [options])

Option is an optional object of PositionOptions objects which includes below parameters

  • maximumAge: integer (milliseconds) | infinity – maximum cached position age.
  • timeout: integer (milliseconds) – amount of time before the error callback is invoked, if 0 it will never invoke.
  • enableHighAccuracy: false | true

Sample option parameter passed to navigator api is given below and make necessary modification as per your requirement.

options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};
  <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>
 

Also, we have used a isRendered flag which will helps to restrict to access the location api multiple times otherwise browser will be blocked and restricts other components from rendering on the browser.

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API

Geolocation API

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

WebExtensions that wish to use the Geolocation object must add the "geolocation" permission to their manifest. The user's operating system will prompt the user to allow location access the first time it is requested.

Concepts and usage

You will often want to retrieve a user's location information in your web app, for example to plot their location on a map, or display personalized information relevant to their location.

The Geolocation API is accessed via a call to navigator.geolocation; this will cause the user's browser to ask them for permission to access their location data. If they accept, then the browser will use the best available functionality on the device to access this information (for example, GPS).

The developer can now access this location information in a couple of different ways:

  • Geolocation.getCurrentPosition(): Retrieves the device's current location.
  • Geolocation.watchPosition(): Registers a handler function that will be called automatically each time the position of the device changes, returning the updated location.

In both cases, the method call takes up to three arguments:

  • A mandatory success callback: If the location retrieval is successful, the callback executes with a GeolocationPosition object as its only parameter, providing access to the location data.
  • An optional error callback: If the location retrieval is unsuccessful, the callback executes with a GeolocationPositionError object as its only parameter, providing access information on what went wrong.
  • An optional object which provides options for retrieval of the position data.

For further information on Geolocation usage, read Using the Geolocation API.

Interfaces

Geolocation

The main class of this API — contains methods to retrieve the user's current position, watch for changes in their position, and clear a previously-set watch.

GeolocationPosition

Represents the position of a user. A GeolocationPosition instance is returned by a successful call to one of the methods contained inside Geolocation, inside a success callback, and contains a timestamp plus a GeolocationCoordinates object instance.

GeolocationCoordinates

Represents the coordinates of a user's position; a GeolocationCoordinates instance contains latitude, longitude, and other important related information.

GeolocationPositionError

A GeolocationPositionError is returned by an unsuccessful call to one of the methods contained inside Geolocation, inside an error callback, and contains an error code and message.

Navigator.geolocation

The entry point into the API. Returns a Geolocation object instance, from which all other functionality can be accessed.

Examples

See Using the Geolocation API for example code.

Specifications

Specification

Geolocation API
# geolocation_interface

Browser compatibility

Report problems with this compatibility data on GitHub

desktopmobileChromeEdgeFirefoxInternet ExplorerOperaSafariWebView AndroidChrome AndroidFirefox for AndroidOpera AndroidSafari on iOSSamsung InternetGeolocationclearWatchgetCurrentPositionSecure context requiredwatchPosition
 
 
5
 
Toggle history
12
 
Toggle history
3.5
footnote
Toggle history
9
 
Toggle history
10.6
 
Toggle history
5
 
Toggle history
37
 
Toggle history
18
 
Toggle history
4
 
Toggle history
11
 
Toggle history
3
 
Toggle history
1.0
 
Toggle history
5
 
Toggle history
12
 
Toggle history
3.5
 
Toggle history
9
 
Toggle history
10.6
 
Toggle history
5
 
Toggle history
37
 
Toggle history
18
 
Toggle history
4
 
Toggle history
11
 
Toggle history
3
 
Toggle history
1.0
 
Toggle history
5
 
Toggle history
12
 
Toggle history
3.5
 
Toggle history
9
 
Toggle history
10.6
 
Toggle history
5
 
Toggle history
37
 
Toggle history
18
 
Toggle history
4
 
Toggle history
11
 
Toggle history
3
 
Toggle history
1.0
 
Toggle history
50
 
Toggle history
79
 
Toggle history
55
 
Toggle history
No
 
Toggle history
37
 
Toggle history
10
 
Toggle history
51
footnote
Toggle history
50
 
Toggle history
55
 
Toggle history
37
 
Toggle history
10
 
Toggle history
5.0
 
Toggle history
5
 
Toggle history
12
 
Toggle history
3.5
 
Toggle history
9
 
Toggle history
10.6
 
Toggle history
5
 
Toggle history
37
 
Toggle history
18
 
Toggle history
4
 
Toggle history
11
 
Toggle history
3
 
Toggle history
1.0
 
Toggle history

Legend

Full supportFull support
No supportNo support
See implementation notes.
 

 

 

 

반응형