Get Current Location Coordinates in Lightning Web Component.

Posted on April 16, 2022 Post Thumbnail

Yo Trailblazers,

Welcome back to heySalesforce (-_-)

In this blog post, I'm going to create a Lightning Web Component, In this component, We can get current location(Coordinates) of user based on browser location(Coordinates).

Before reading this blog post, Have a look at following demo.

https://miricommunity01102020-developer-edition.ap15.force.com/mapmarkerlwc/s/currentlocation

Latitude and Longitude in LWC

What you'll Learn from Blog Post :)

1. Map in Vf Page with draggable marker on Map.

2. Communication between LWC and Vf Page.

3. How to access current location of a user.

Let's Start :)

In my previous blog post. I created a Lightning Web Component to show a map with draggable marker. Have a look at following blog post.

Implement Draggable Marker On Map And Move Marker On Map In Lightning Web Component.

Someone asked me a question to Create a Lightning Web Component to get current location, That's why I'm writing this blog post.

Current Location in LWC

https://heysalesforce.org/questions/requirement-in-getting-current-location

For this blog post, I'll use following code from developer.mozilla.org

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);

With the help of this code snippet, We can get Current Location in JS.

Current Location in LWC

Let's Create a Visualforce Page.

currentLocationMapPage

<apex:page lightningStylesheets="true" showHeader="false" sidebar="false">
    <apex:slds />
    <head>
        <style type="text/css">
            html { height: 100% }
            body { height: 100%; margin: 0; padding: 0 }
            #map-canvas { width:100%;height:100%; }
        </style>
        <script src="https://maps.googleapis.com/maps/api/js"></script>
        <script>
            var map;
        var latitude ;
        var longitude ;
        //Getting parameters for initial position on map.
        //var latitude = '{!$CurrentPage.parameters.latitude}';
        //var longitude = '{!$CurrentPage.parameters.longitude}';
        //console.log(latitude);
        //console.log(longitude);
        var options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        };
        
        function success(pos) {
            var crd = pos.coords;
            
            console.log('Your current position is:');
            console.log(`Latitude : ${crd.latitude}`);
            console.log(`Longitude: ${crd.longitude}`);
            console.log(`More or less ${crd.accuracy} meters.`);
            latitude = crd.latitude;
            longitude = crd.longitude;
            
            let coords = latitude +'|'+longitude;
            sendToLigntningWC(coords);
            initialize();
        }
        
        function error(err) {
            console.warn(`ERROR(${err.code}): ${err.message}`);
        }
        
        navigator.geolocation.getCurrentPosition(success, error, options);
        let fullurl = window.location.href;
        //console.log('VF Url: '+fullurl);
        var lwcOrigin = fullurl.slice(0,fullurl.indexOf(".com/")+4);
        let host = '{!$CurrentPage.parameters.host}';
        //Checking if component placed on lightning /in community site.
        if(host ==='lightning')
            lwcOrigin = lwcOrigin.replace("--c.visualforce.com",".lightning.force.com");
        //Sending coordinates to Lightning Component.
        function sendToLigntningWC(latlng){
            //console.log('LWC Origin: '+lwcOrigin);
            let lightningOrigin = lwcOrigin;
            let messgaeToLWC = latlng;
            window.parent.postMessage(messgaeToLWC,lightningOrigin);
        }
        //initializing map
        google.maps.event.addDomListener(window, 'load', initialize);
        function initialize() {
            const myLatlng = { lat: parseFloat(latitude), lng: parseFloat(longitude)};
            const map = new google.maps.Map(document.getElementById("map-canvas"), {
                zoom: 15,
                center: myLatlng,
            });
            const infowindow = new google.maps.InfoWindow({
                content: 'Drag Marker to get coordinates.',
            });
            let marker = new google.maps.Marker({
                map,
                draggable: true,
                animation: google.maps.Animation.DROP,
                position:myLatlng
            });
            //function works on dragging of marker
            marker.addListener("drag", () => {
                latitude = marker.get("position").toJSON().lat;
                longitude = marker.get("position").toJSON().lng;
                let coords = latitude +'|'+longitude;
                sendToLigntningWC(coords);
            });
                marker.addListener("click", () => {
                infowindow.open({
                anchor: marker,
                map,
                shouldFocus: false,
            });
        }); 
        }   
        </script>
    </head>
    <body>
        <div id="map-canvas"/>
    </body>
</apex:page>

We need this Visualforce Page for the Source Url of Iframe in LWC Component.

Now, Let's Create a LWC Component.

GetCurrentLocation.html

<template>
    <lightning-card>
        <h3 slot="title">
            <lightning-icon class="slds-m-right_small" icon-name="action:map" size="large"></lightning-icon>
            Current Location on Map in LWC!
        </h3>
        <lightning-input-location class="slds-m-horizontal_x-large slds-m-bottom_large" label="Default coordinates" latitude={latitude} longitude={longitude}></lightning-input-location>
            <iframe class="slds-m-horizontal_x-large slds-box" height="400px"  scrolling="no" src={mainIframeUrl} frameborder="0"  width="90%">
            </iframe>
    </lightning-card>
</template>

GetCurrentLocation.js

import { LightningElement,track } from 'lwc';

export default class GetCurrentLocation extends LightningElement {
    vfUrl = '/apex/currentLocationMapPage';
    mainIframeUrl = '';
    latitude = '';
    longitude = '';
    connectedCallback() {
        let href = window.location.href;
        this.mainIframeUrl = this.vfUrl + '&host=classic';
        if (href.includes("lightning.force.com")) {
            this.mainIframeUrl = this.vfUrl + '&host=lightning';
        }
        window.addEventListener("message", this.handleCoordinates.bind(this), false);
    }
   
    handleCoordinates(message) {
        if (message.data != null && !message.data.includes("{")) {
            let coords = message.data;
            this.latitude = coords.slice(0, coords.indexOf("|"));
            this.longitude = coords.slice(coords.indexOf("|") + 1, coords.length);
        }
    }
}

GetCurrentLocation.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Current location Map in LWC</masterLabel>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
        <target>lightningCommunity__Page</target>
        <target>lightning__FlowScreen</target>
    </targets>
</LightningComponentBundle>

After Creating Visualforce Page and LWC Component.

Final component Demo.

LWC

Marker on the map is also draggable.

Use Api key in following code if you want to see clear Map.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY"></script>

Have a look at the demo Again.

Note: This is just for Study Purposes And I above code may not follow best practices.

If you have any question Ask Me

Thanks for Reading :)

Write a comment for suggestions and hit the heart icon.


671
0

Tags: #salesforce #lwc

Comments

There are no comments yet.
Your message is required.

Get notified of new posts