Skip to content

Instantly share code, notes, and snippets.

/Location Secret

Created July 23, 2016 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/708ef8e80e05da0649c14becc7d7724e to your computer and use it in GitHub Desktop.
Save anonymous/708ef8e80e05da0649c14becc7d7724e to your computer and use it in GitHub Desktop.
// APEX CLASS IS HERE !
public class geolucationtry {
@future (callout=true) // future method needed to run callouts from Triggers
static public void getLocation(id accountId){
// gather account info
Account a = [SELECT BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet FROM Account WHERE id =: accountId];
// create an address string
String address = '';
if (a.BillingStreet != null)
address += a.BillingStreet +', ';
if (a.BillingCity != null)
address += a.BillingCity +', ';
if (a.BillingState != null)
address += a.BillingState +' ';
if (a.BillingPostalCode != null)
address += a.BillingPostalCode +', ';
if (a.BillingCountry != null)
address += a.BillingCountry;
address = EncodingUtil.urlEncode(address, 'UTF-8');
// build callout
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false');
req.setMethod('GET');
req.setTimeout(60000);
try{
// callout
HttpResponse res = h.send(req);
// parse coordinates from response
JSONParser parser = JSON.createParser(res.getBody());
double lat = null;
double lon = null;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'location')){
parser.nextToken(); // object start
while (parser.nextToken() != JSONToken.END_OBJECT){
String txt = parser.getText();
parser.nextToken();
if (txt == 'lat')
lat = parser.getDoubleValue();
else if (txt == 'lng')
lon = parser.getDoubleValue();
}
}
}
// update coordinates if we get back
if (lat != null){
a.Location__Latitude__s = lat;
a.Location__Longitude__s = lon;
update a;
}
} catch (Exception e) {
}
}
}
// THIS IS MY TRIGGER CODE :
trigger location_set on Account (after insert, after update)
{
for (Account a : trigger.new)
if (a.Location__Latitude__s == null)
geolucationtry.getLocation(a.id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment