A blog about Salesforce CRM Configuration and development

Friday, 21 September 2018

Get geolocation coordinates in the Visualforce Page

Scenario: Sometimes we need to track current location on SFDC record field update, in that case, we have to get the current coordinates where the record field is updated/inserted.

In this blog, I am going to implement the above functionality using custom visualforce page with standard controller and extension. Javascript is going to be used to get the current coordinates based on the events fired by the user (field insert/update).

The main pain point is to get the coordinates on Text Area (Rich) field on change (change event) because 'onchange' will not work with Text Area (Rich) field, so I am using CKEditor here to track the changes in the Text Area (Rich) field.

Visualforce page:
 <apex:page standardController="Account" extensions="GeoLocationCntrlExtn" sidebar="false">  
  <html>  
    <head>  
      <apex:slds />  
      <style>  
        .slds-scope .slds-table_bordered tbody td, .slds-scope .slds-table_bordered tbody th, .slds-scope .slds-table--bordered tbody td, .slds-scope .slds-table--bordered tbody th{  
           border-top: 0px;  
         }  
          .slds-scope .slds-page-header{  
         border-radius: 0px;  
         box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.1);  
         }  
         .bodyPart{  
           border: 1px solid #E5E5E5;  
         }  
      </style>  
    </head>  
    <body>  
      <div class="slds bodyPart">  
        <div class="slds-grid">  
          <div class="slds-col slds-size--12-of-12">  
            <div class="slds-page-header">  
              <span style=""> New Account </span>  
            </div>  
          </div>  
        </div>  
        <div class="slds-grid">  
          <div class="slds-col slds--size-12-of-12">  
            <apex:form >  
              <!-- ******************* Action Function ********************************************-->  
               <apex:actionFunction action="{!calLocation}" name="calculateLocation" reRender="">  
                 <apex:param value="" name="longitude" assignTo="{!longitude}" />  
                 <apex:param value="" name="latitude" assignTo="{!latitude}" />  
              </apex:actionFunction>  
              <apex:outputpanel id="test">  
              </apex:outputpanel>  
              <!-- **********************************************************************************-->  
              <span style="color:red;" id="locationError"> </span>  
              <table class="slds-table slds-table--bordered slds-no-row-hover slds-max-medium-table_stacked">  
                <tbody>  
                  <tr>  
                    <td>Name</td>  
                    <td><apex:inputfield value="{!Account.Name}" styleClass="slds-input"/></td>  
                  </tr>  
                  <tr>  
                    <td>Site Address</td>  
                    <td><apex:inputfield value="{!Account.Address__c}" styleClass="slds-input"/></td>  
                  </tr>  
                </tbody>  
              </table><br/>  
              <center>  
                <apex:commandButton value="Save" action="{!SaveRecord}" styleClass="slds-button slds-button--brand" />  
                <apex:commandButton value="Cancel" action="{!CancelAction}" styleClass="slds-button slds-button--neutral" immediate="true"/>  
            </center><br/>  
            </apex:form>  
          </div>  
        </div>  
      </div>  
      <!--*********** JS script **************>  
      <script>  
       for (var i in CKEDITOR.instances) {  
         CKEDITOR.instances[i].on('change', function() {  
           var x=document.getElementById('locationError');  
             if (!navigator.geolocation){  
             return;  
             }  
              function success(position) {  
               var latitude = position.coords.latitude;  
               var longitude = position.coords.longitude;  
               //alert('latitude: '+ latitude );  
               //alert('longitude: '+ longitude );  
               calculateLocation(longitude,latitude);  
             }  
             function error() {  
             //alert(error.code);  
             switch(error.code) {  
                 case error.PERMISSION_DENIED:  
                   x.innerHTML = "User denied the request for Geolocation."  
                   break;  
                 case error.POSITION_UNAVAILABLE:  
                   x.innerHTML = "Location information is unavailable."  
                   break;  
                 case error.TIMEOUT:  
                   x.innerHTML = "The request to get user location timed out."  
                   break;  
                 case error.UNKNOWN_ERROR:  
                   x.innerHTML = "An unknown error occurred."  
                   break;  
                 }  
             }  
             navigator.geolocation.getCurrentPosition(success, error);  
         });  
        }  
   </script>  
    </body>  
  </html>  
 </apex:page>  

********************* Apex Controller **************************************

 public with sharing class GeoLocationCntrlExtn {  
   public String longitude{get;set;}  
   public String latitude{get;set;}  
   private Account acc;  
   public GeoLocationCntrlExtn(ApexPages.StandardController controller) {  
     this.acc = (Account)controller.getRecord();  
   }  
   public pageReference calLocation(){  
     return null;  
   }  
   public pageReference SaveRecord(){  
      if((acc.Address__c!=null && acc.Address__c!='') )  
        acc.Address__c += ' latitude: '+latitude+' longitude: '+longitude;  
      try{  
        insert acc;  
          PageReference pageRef = new PageReference('/'+ acc.Id );  
          return pageRef ;  
        }  
        catch(DMLException dmle){  
          ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Error: ' + dmle.getdmlMessage(0) ));  
         system.debug('Exception has occured! '+dmle.getMessage() );  
        return null;  
        }  
   }  
    public pageReference CancelAction(){  
     return null;  
   }  
 }  






Share:

0 comments:

Post a comment

Trailhead Profile


Follow by Email

Total Pageviews

Followers

Popular Posts

Powered by Blogger.

Contact form

Name

Email *

Message *