To get Geo-location from google API in Salesforce, I did a small integration with Google Geocode API.
To call Google API, we need the API key. Follow the steps in this article to get the key.
Steps to get the latitude and longitude from Google Geolocation
Create an Apex trigger with below code. The trigger runs after insert or update.
// Trigger runs getLocation() on Accounts with no Geolocation
trigger SetGeolocation on Account (after insert, after update) {
//bulkify trigger in case of multiple accounts
for(Account account : trigger.new) {
//check if Billing Address has been updated
Boolean addressChangedFlag = false;
if(Trigger.isUpdate) {
Account oldAccount = Trigger.oldMap.get(account.Id);
if((account.billingaddress__c!= oldAccount.billingaddress__c) || (account.City__c!= oldAccount.City__c) ||
(account.State__c!= oldAccount.State__c) ||(account.Zip_Code__c!= oldAccount.Zip_Code__c)||(account.Country__c!= oldAccount.Country__c)){
addressChangedFlag = true;
}
}
// if Location is null or address has been changed, call the Geocode class
if((account.Location__Latitude__s == null) || (addressChangedFlag == true)) {
AccountGeocodeAddress.DoAddressGeocode(account.id);
}
}
}
public class AccountGeocodeAddress {
private static Boolean geocoding= false;
public static void DoAddressGeocode(id accountId) {
if(geocodingCalled || System.isFuture()) {
System.debug(LoggingLevel.WARN, 'Method Already Called');
return;
}
//Else call the future method
geocoding = true;
geocodeAddress.geocodeAddress(accountId);
}
}
The following class is where future call out occurs. As a result, lat long are saved in Account record.
public class geocodeAddress {
// we need a future method to call Google Geocoding API from Salesforce
@future (callout=true)
static public void geocodeAddress(Id accountId)
{
// Key for Google Maps Geocoding API
String geocodingKey = <Your API Key>
Account geoAccount = [SELECT billingaddress__c, City__c, State__c, Country__c,Zip_Code__c,Location_Status__c FROM Account WHERE
id = :accountId];
//create a string for the address to pass to Google Geocoding API
String geoAddress = '';
if(geoAccount.billingaddress__c!= null)
geoAddress+= geoAccount.billingaddress__c+ ', ';
if(geoAccount.City__c != null)
geoAddress+= geoAccount.City__c+ ', ';
if(geoAccount.State__c!= null)
geoAddress+= geoAccount.State__c+ ', ';
if(geoAccount.Country__c!= null)
geoAddress+= geoAccount.Country__c+ ', ';
if(geoAccount.Zip_Code__c!= null)
geoAddress+= geoAccount.Zip_Code__c;
//encode the string so we can pass it as part of URL
geoAddress= EncodingUtil.urlEncode(geoAddress, 'UTF-8');
//make the callout to the Geocoding API
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address='+geoAddress +'&key='+ geocodingKey+'&sensor=false');
request.setMethod('GET');
request.setTimeout(60000);
try {
// make the http callout
HttpResponse response = http.send(request);
System.debug(response.getBody());
// parse JSON to extract co-ordinates
JSONParser responseParser = JSON.createParser(response.getBody());
// initialize co-ordinates
double latitude = null;
double longitude = null;
while (responseParser.nextToken() != null) {
if((responseParser.getCurrentToken() == JSONToken.FIELD_NAME) &&(responseParser.getText()== 'location')) {
responseParser.nextToken();
while(responseParser.nextToken() != JSONToken.END_OBJECT) {
String locationText = responseParser.getText();
responseParser.nextToken();
if (locationText == 'lat')
latitude = responseParser.getDoubleValue();
else if (locationText == 'lng')
longitude = responseParser.getDoubleValue();
}
}
else
{
geoAccount.Location_Status__c='Address Invalid';
}
}
//update co-ordinates on address if we get them back
if(latitude != null) {
geoAccount.Location__Latitude__s= latitude;
geoAccount.Location__Longitude__s= longitude;
geoAccount.Location_Status__c='Location Updated';
}
} catch
(Exception e) {
System.debug(LoggingLevel.ERROR,
'Error Geocoding Address - ' + e.getMessage());
}
update geoAccount;
}
}
Now whenever new account is inserted or address is updated, API will be called to get the location coordinates.