Created
January 17, 2018 17:17
-
-
Save jsmithdev/053c8e5b0552770be420a9e0ca845a22 to your computer and use it in GitHub Desktop.
Apex class for SalesForce that takes an Address and get's Geolocation from Google Maps API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Location { | |
@InvocableMethod | |
public static void getLatLong(List<Id> Ids){ | |
//Get opp | |
Opportunity opp = [ | |
SELECT Id, jamiesmith__Location__Latitude__s, jamiesmith__Location__Longitude__s, jamiesmith__Street__c, jamiesmith__City__c, jamiesmith__State__c | |
FROM Opportunity | |
WHERE Id IN :Ids | |
LIMIT 1 | |
]; | |
//Build address & encode it | |
String address = opp.jamiesmith__Street__c +' '+ opp.jamiesmith__City__c +' '+ opp.jamiesmith__State__c; | |
address = EncodingUtil.urlEncode(address,'UTF-8'); | |
// Get API key from custom setting | |
String apiKey = [SELECT jamiesmith__Key__c FROM jamiesmith__GoogleMapAPI__c ORDER BY LastModifiedDate LIMIT 1].jamiesmith__Key__c; | |
//Build request | |
HttpRequest request = new HttpRequest(); | |
request.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?key='+apiKey+'&address='+address+'&sensor=false'); | |
request.setMethod('GET'); | |
request.setCompressed(false); | |
request.setHeader('Encoding','iso-8859-1'); | |
request.setHeader('Content-Type', 'application/x-www-form-urlencoded'); | |
request.setTimeout(120000); | |
HttpResponse response = new http().send(request); | |
if(response.getStatusCode() == 200) { | |
JSONParser parser = JSON.createParser(response.getBody()); | |
Boolean hasLat = false; | |
Boolean hasLng = false; | |
//Parse response, updatea opp's lat/lng | |
while (parser.nextToken() != null) { | |
String key = String.valueOf(parser.getCurrentName()); | |
if (key == 'lat' && parser.getText() != 'lat' && !hasLat){ | |
hasLat = true; | |
opp.jamiesmith__Location__Latitude__s = Double.valueOf(parser.getText()); | |
} | |
else if (key == 'lng' && parser.getText() != 'lng' && !hasLng){ | |
hasLng = true; | |
opp.jamiesmith__Location__Longitude__s = Double.valueOf(parser.getText()); | |
} | |
if(hasLat && hasLng){ | |
break; | |
} | |
} | |
//Commit changes to DB | |
update opp; | |
} | |
else { | |
System.debug('Status NOT 200!'); | |
System.debug(response); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment