Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SSEGeoService allows you to set the new Geolocation fields of any object by running an address string through the Google Geolocation API.
public class SSEGeoService
{
class GeoException extends Exception {}
@future (callout=true)
static public void setLocation(String sobj, String field, String id, String address)
{
if (String.isBlank(address)) {
throw new SSEGeoService.GeoException('Address can not be blank.');
}
String latField;
String longField;
if (field.contains('__c')) {
latField = field.replace('__c', '__Latitude__s');
longField = field.replace('__c', '__Longitude__s');
} else {
latField = field + '__Latitude__s';
longField = field + '__Longitude__s';
}
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
if (gd.get(sobj) == null) {
throw new SSEGeoService.GeoException('SObject does not exist: `' + sobj + '`');
}
Map<String, Schema.SObjectField> fmap = gd.get(sobj).getDescribe().fields.getMap();
if (fmap.get(latField) == null) {
throw new SSEGeoService.GeoException('Field does not exist on SObject (`' + sobj + '`): `' + field + '`');
}
SObject obj = Database.query('Select Id, ' + latField + ', ' + longField + ' From ' + sobj + ' Where Id = \'' + id + '\'');
if (obj == null) {
throw new SSEGeoService.GeoException('Record does not exist on SObject (`' + sobj + '`): ID `' + id + '`');
}
address = EncodingUtil.urlEncode(address, 'UTF-8');
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=false');
req.setMethod('GET');
req.setTimeout(60000);
try {
HttpResponse res = h.send(req);
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();
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();
}
}
}
}
if (lat != null && lon != null){
obj.put(latField, lat);
obj.put(longField, lon);
update obj;
}
} catch (Exception e) {
throw new SSEGeoService.GeoException(e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.