Thursday, 13 August 2015

Get Current Geolocation in Salesforce using Geolocation API

Recently was trying to fetch the current location of mine in salesforce, most of the time people use google api's for it, but just dig in a bit and found something way too easy and way too awesome to use, the best part is you can utilize the javascript code without referring any further libraries.

Here I got the example of using geolocation API, this document is the specification defines an API that provides scripted access to geographical location information associated with the hosting device.

here is the sample code that they shared


So to implement this thing I want to check weather it work on normally on Salesforce or not, So I created a detail button on Account to check the code. I created a geolocation type field on Account object, and created a detail button on it adn added it to the layout.

Here is the detail page button "Check-in" and "Geolocation" field, just click on check-in button you will the current geolocation, to know more about the geolocation field click here


Here is the code of the check-in detail button, please put Behavior as Execute JavaScript of the detail button.

1:  {  
2:    !requireScript("/soap/ajax/26.0/connection.js")  
3:  }  
4:  navigator.geolocation.getCurrentPosition(function(position) {  
5:    var longitude = position.coords.longitude;  
6:    var latitude = position.coords.latitude;  
7:    var account = new sforce.SObject("Account");  
8:    account.id = '{!Account.Id}';  
9:    account.Geolocation__Latitude__s = latitude;  
11:   account.Geolocation__Longitude__s = longitude;  
12:   var result = sforce.connection.update([account]);  
13:   if (result[0].getBoolean("success")) {  
14:        alert('Account updated successfully');  
15:        window.location.reload();  
16:   } else {  
17:       alert('Error : ' + result);  
18:   }  
19: });  

Just try above code, it works like charm. Happy to answer any query.
Hope this will help someone.

Happy coding!!

No comments:

Post a Comment