Created
November 22, 2012 16:40
-
-
Save tstachl/4132052 to your computer and use it in GitHub Desktop.
SSEGeoService allows you to set the new Geolocation fields of any object by running an address string through the Google Geolocation 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 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