Skip to content

Instantly share code, notes, and snippets.

/Dest_Location Secret

Created July 23, 2016 15:24
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/a0ee0c13d393468807efe1437ec0a5d2 to your computer and use it in GitHub Desktop.
Save anonymous/a0ee0c13d393468807efe1437ec0a5d2 to your computer and use it in GitHub Desktop.
// APEX CODE IS HERE!!!
public class dest_geolucationtry
{
@future (callout=true) // future method needed to run callouts from Triggers
static public void getLocation(id accountId){
// gather account info
Account b = [SELECT ShippingCity,ShippingCountry,ShippingPostalCode,ShippingState,ShippingStreet FROM Account WHERE id =: accountId];
// create an address string
String address = '';
if (b.ShippingStreet != null)
address += b.ShippingStreet +', ';
if (b.ShippingCity != null)
address += b.ShippingCity +', ';
if (b.ShippingState != null)
address += b.ShippingState +' ';
if (b.ShippingPostalCode != null)
address += b.ShippingPostalCode +', ';
if (b.ShippingCountry != null)
address += b.ShippingCountry;
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 lati = null;
double longi = 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')
lati = parser.getDoubleValue();
else if (txt == 'lng')
longi = parser.getDoubleValue();
}
}
}
// update coordinates if we get back
if (lati != null){
b.Dest_Location__Latitude__s = lati;
b.Dest_Location__Longitude__s = longi;
update b;
system.debug(b);
}
} catch (Exception e) {
}
}
}
// THIS IS TRIGGER CODE :
trigger location_set on Account (after insert, after update)
{
for (Account b : trigger.new)
if (b.Dest_Location__Latitude__s == null)
dest_geolucationtry.getLocation(b.id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment