+ Start a Discussion
Jon-Michael MurpheyJon-Michael Murphey 

capture current geolocation with global action

Im needing to create a Global Action or button in my lightning experince on a custom object. Once clicked will update the lat/long fields with the users current location
NagendraNagendra (Salesforce Developers) 
Hi Jon,

Please find the sample code below and tweak it as per your requirement.

Component:
<aura:component controller="user_current_location" implements="force:lightningQuickAction,force:hasRecordId" access="global">
<aura:attribute name="visit" type="Visit__c"/>
  <aura:handler name="init" value="{!this}" action="{!c.doInit}" /> 
   <aura:handler name="init" value="{!this}" action="{!c.getLocation}" />
    
    <div class="slds-page-header" role="banner">
    <h1 class="slds-page-heading--label">Check-In Update</h1>
    </div>
    
    <lightning:input type="text" name="id" aura:id="id" label="Name" value="{!v.visit.Name}" ></lightning:input>
    <lightning:input type="number" name="latitude" aura:id="latitude" label="Check-In Latitude" value="{!v.visit.Check_in_GeoLocation__latitude__s}" ></lightning:input>
    <lightning:input type="text" name="longitude" aura:id="longitude" label="Check-In Longitude" value="{!v.text}"></lightning:input>
    <lightning:input type="date" name="checkindate" aura:id="checkindate" label=" {!v.visit.Check_in_Date_Time__c}" ></lightning:input>
</aura:component>
Controller:
({
  doInit : function(component, event, helper) {
        console.log('init');
         var action = component.get("c.getVisit");   
         action.setParams({"visitId" : component.get("v.recordId")});
         action.setCallback(this, function(response) {
         console.log(response.getReturnValue());
         component.set("v.visit", response.getReturnValue());
         });

        $A.enqueueAction(action);
    },

   getLocation: function(component, event, helper){
   if (navigator.geolocation) {
       navigator.geolocation.getCurrentPosition(function(position) {
           var lat = position.coords.latitude;
           var lon = position.coords.longitude;
 //           alert(lat);
 //           alert(lon);
            component.set("v.lat", lat ) ;
}
})
ApexC:
public with sharing class user_current_location {
 
    @AuraEnabled
    public static Visit__c getVisit(Id visitId){

        return [SELECT Name, Id, Check_in_GeoLocation__latitude__s, Check_in_GeoLocation__longitude__s, Check_in_Date_Time__c FROM Visit__c
        WHERE Id = :visitId ];
    }
}
Hope this helps.

Kindly mark this as solved if the reply was helpful so that it gets removed from the unanswered queue so that it results in helping others who are encountering a similar issue.

Thanks,
Nagendra