-
-
Save anonymous/708ef8e80e05da0649c14becc7d7724e to your computer and use it in GitHub Desktop.
This file contains 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
// 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