Ad Code

Responsive Advertisement

checkIn and Checkout feature with geolocation and time in salesforce



Requirement:
Let's Suppose there is manufacturer industry and in this industry, there are 40 Sales Rep who do Sales activity for the company. so Each Sales Rep has there PJP( Permanent journey Plan). In this journey, each Sales Rep has to go and follow the Route Planned from start point to end point for Order Booking from Retailer.

Problem:
Regional Sales Manager would like to track the position(geolocation) of the Sales Rep. By what time he has started the journey and where has ended with the order booking. as well as there checkIn Time and CheckOut Time with geolocation.

Solution:
In my solution, I would like to show how CheckIn and CheckOut will work through visualforce page.
This checkIn , Checkout feature is to tag the Geolocation of the user.

Solution Step by Step:

1. Create Contact Check In Object API Name Contact_Check_In__c
2. Define following field on this Object


Address Address__c Text Area(255)
CheckIn Date Time CheckIn_Date_Time__c Date/Time
Checkout Address Checkout_Address__c Text Area(255)
Checkout Date time Checkout_Date_time__c Date/Time
Contact Contact__c Lookup(Contact)
Contact Check In Name Name Auto Number
GeoLocation GeoLocation__c Geolocation
Opportunity Opportunity__c Lookup(Opportunity

  • Create a VF Page with the following code:

VF Page Name: OpportunityCheckIn and following apex class: OpportunityCheckInController

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<apex:page standardController="opportunity" extensions="OpportunityCheckInController" lightningStylesheets="true">
  <apex:includeScript value="{!$Resource.gmap}"/>
  <apex:slds />

  <input type="button" value="Check In" onclick="checkIn()" class="slds-button slds-button_stateful .slds-is-selected slds-button_success"/>
  <input type="button" value="Check Out" onclick="checkOut()" class="slds-button slds-button_stateful .slds-is-selected slds-button_destructive"/>
  
  <script>
      function checkIn(){
          
          var oppId='{!OppId}';
          
          GMaps.geolocate({
          success: function(position) {
            alert('Doing Checkin for following lat: ' + position.coords.latitude +' and long: ' + position.coords.longitude );
            
            var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var address='';
            var geocoder = geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        address=results[1].formatted_address;
                                     Visualforce.remoting.Manager.invokeAction(
                            '{!$RemoteAction.OpportunityCheckInController.addCheckIns}',oppId,position.coords.latitude,  position.coords.longitude, address,function(result, event) {console.log(result);alert('Check In Done. Successfully!');}
                            );
                    }
                }
            });
            
           
           
        
            //alert('long' + position.coords.longitude);
            
            map.setCenter(position.coords.latitude, position.coords.longitude);
          },
          error: function(error) {
            alert('Geolocation failed: '+error.message);
          },
          not_supported: function() {
            alert("Your browser does not support geolocation");
          },
          always: function() {
            alert("Done!");
          }
        });
        
      }
      
      function checkOut(){
          
          var oppId='{!OppId}';
          
          GMaps.geolocate({
          success: function(position) {
            alert('Doing CheckOut for following lat: ' + position.coords.latitude +' and long: ' + position.coords.longitude );
            
            var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var address='';
            var geocoder = geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        address=results[1].formatted_address;
                                     Visualforce.remoting.Manager.invokeAction(
                            '{!$RemoteAction.OpportunityCheckInController.addCheckOuts}',oppId,position.coords.latitude,  position.coords.longitude, address,function(result, event) {console.log(result);alert('Check Out Done. Successfully!');}
                            );
                    }
                }
            });
            
           
           
        
            //alert('long' + position.coords.longitude);
            
            map.setCenter(position.coords.latitude, position.coords.longitude);
          },
          error: function(error) {
            alert('Geolocation failed: '+error.message);
          },
          not_supported: function() {
            alert("Your browser does not support geolocation");
          },
          always: function() {
            alert("Done!");
          }
        });
        
      }
      
  </script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBqqej11sosokXGaQTk_-Zw9AIXMVkXoAE&callback=loadMap">
    </script>
  <div id="map"/>
</apex:page>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class OpportunityCheckInController {

    public Id OppId{get;set;}

    public OpportunityCheckInController(ApexPages.StandardController controller) {
     OppId='0067F000006Qd3NQAS';
     OppId=controller.getRecord().Id;
    }


    @RemoteAction
    public static void addCheckIns(string OppId,decimal lat, decimal lng,string address){
        Contact_Check_In__c ConCheckIn=new Contact_Check_In__c();
        ConCheckIn.CheckIn_Date_Time__c=system.now();
        ConCheckIn.GeoLocation__latitude__s=lat;
        ConCheckIn.GeoLocation__longitude__s=lng;
        //ConCheckIn.Contact__c=ContId;
        ConCheckIn.Opportunity__c=OppId;
        ConCheckIn.Address__c=address;
        insert ConCheckIn;
    }
    
    @RemoteAction
    public static void addCheckOuts(string OppId,decimal lat, decimal lng,string address){
        Contact_Check_In__c ConCheckIn=new Contact_Check_In__c();
        ConCheckIn.Checkout_Date_time__c=system.now();
        ConCheckIn.GeoLocation__latitude__s=lat;
        ConCheckIn.GeoLocation__longitude__s=lng;
        //ConCheckIn.Contact__c=ContId;
        ConCheckIn.Opportunity__c=OppId;
        ConCheckIn.Checkout_Address__c=address;
        insert ConCheckIn;
    }
    
    
    
}






Now embed this VF page on your Opportunity Page. your opportunity Page will look this.





Once user will hit checkIn button it will save the CheckIn time, geolocation in Contact Checkin Object.

Now Regional Sales Manager have a Tab where he can see there Sales Rep position.

this will look like this


For the above, we have following Visual force Page and Apex Class






 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<apex:page controller="MyCheckInController" lightningStylesheets="true" docType="HTML-5.0">

<html>
  <head>
   <title>Check In Detail</title>
   <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 90%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 90%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>

  <body onload = "loadMap()">
    <h2>Sales Rep Check In Detail</h2>
    <div id = "map" ></div>
      <script>

        
        function loadMap() {
          // Initialize Google Maps
          const mapOptions = {
            center:new google.maps.LatLng(28.59244000,77.32267000),
            zoom: 13
          }
          const map = new google.maps.Map(document.getElementById("map"), mapOptions);
          
          var text = '{!JsonCheckInData}';
          var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
            var icons = {
              parking: {
                icon: iconBase + 'parking_lot_maps.png'
              },
              library: {
                icon: iconBase + 'library_maps.png'
              },
              info: {
                icon: iconBase + 'info-i_maps.png'
              }
            };
            
          var obj = JSON.parse(text);
          //alert(obj);
          //return obj;
          var x;
          var jsonData='';
          var loc1='';
          var loc2;
          var address='';
          for (x in obj) {
           
            temp=obj[x].location.split(",");
            loc1=temp[0].replace("[", "");
            loc2=temp[1].replace("]", "");
            
                                   
            let marker = new google.maps.Marker({
              map: map,
              icon:icons['library'].icon,
              position: new google.maps.LatLng(loc1, loc2),
              title: 'Person Name:' +  obj[x].name + ' CheckIn:' +obj[x].checkIn 
            })
            
            
          } 
          
              
        
          
          
        }
      </script>
      <!--<script src = "https://maps.googleapis.com/maps/api/js"></script>-->
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBqqej11sosokXGaQTk_-Zw9AIXMVkXoAE&callback=loadMap">
    </script>
    {!JsonCheckInData}
  </body>
</html>
</apex:page>
This is the Apex class




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class MyCheckInController {

    public list<Contact_Check_In__c> LstContactCheckIn{get;set;}
    
    public string JsonCheckInData{get;set;}

    public MyCheckInController(){
        
        LstContactCheckIn=[Select Id, CheckIn_Date_Time__c, GeoLocation__latitude__s, GeoLocation__longitude__s, Contact__r.Name from Contact_Check_In__c];
        
        list<WrpData> lstWrpData=new list<WrpData>();
        
        for(Contact_Check_In__c Check:LstContactCheckIn){
               string strLocation='[' + string.valueOf(check.GeoLocation__latitude__s) + ','  + string.valueOf(check.GeoLocation__longitude__s)+ ']';
               WrpData wrp=new WrpData(check.Contact__r.Name, strLocation, string.ValueOf(check.CheckIn_Date_Time__c),string.valueOf(check.GeoLocation__latitude__s),string.valueOf(check.GeoLocation__longitude__s));
               lstWrpData.add(wrp);
        }
        
        JsonCheckInData=Json.Serialize(lstWrpData);
        
    }
    
    public class WrpData{
        
        public string name{get;set;}
        public string location{get;set;}
        public string checkIn{get;set;}
        public string lat{get;set;}
        public string lng{get;set;}
        public WrpData(string nm,string loc,string chkIn, string lt,string ln){
            name=nm;
            location=loc;
            checkIn=chkIn;
            lat=lt;
            lng=ln;
        }
    }
    
    
    
    
    
    
    
    
}


Note: from both the VF page please change your key. you can grab this key from Google map Account.

src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBqqej11sosokXGaQTk_-Zw9AIXMVkXoAE&callback=loadMap


here is the gmap JS file . Static Resource


ResorceMap
happy coding!! happy sharing.
Reactions

Post a Comment

5 Comments

  1. hello amul, first congrats for development.
    I would like know about the tab Sales Rep Position.

    I dont managed to replicate it in my organization, could you help-me, please?

    ReplyDelete
  2. Hello Amul

    Great Blog, i exactly Replicated what you have instructed, but when i click checkin button, the cordinates are not properly recording, i even tried changing the Google API key, still not helpfull, can you please help,

    ReplyDelete
    Replies
    1. Did you have solved the problem Manjunath

      Delete
  3. Hii Amul,,

    Nice Blog!! I Already using your code, but why i cant get the record on the object?

    ReplyDelete