+ Start a Discussion

Apex and geolocation

I'm looking for some pointers on geolocating within an SFDC Apex custom application.  Specifically, I want to link an instance of one custom object with an instance of another custom object based on a geolocation computation each object's address.  Think matching a customer to the nearest store, given an address for the customer and a list of store addresses. 


It doesn't look like SFDC has gotten around to any Apex-specific geocoding / query methods, but maybe I'm wrong or missed something.


Alternatively, has anyone had any luck doing something like the above via webservice calls from Apex to external (3rd party or role-your-own) geo services?  If so, any general guidelines for architecture/implementation?


Thx for any pointers.

Cory CowgillCory Cowgill

I have done this type of work with Apex, also the App Exchange app "FindNearby" provides this type of functionality.


Currently I've built a VF / Apex / Third Party API / Google Maps application which does all this functionality on Force.com.


In short:


1. You have a custom object or standard object in Salesforce. Add two fields to the object (one for latitude, one for longitude) of type Decimal. Do this for the differnent types of records you are going to work with. So if you have Customer (IE Contacts) they have Lat/Long fields.


2. You can execute Apex & SOQL to query for all objects around a bounded box of coordinates and in VF page with Javascript add them to a Google Map.


Apex Example to query custom objects within a range:

public PageReference iFoundYou()
     System.debug('IFoundYou called....');
    decimal bottomLat = -0.0015 + Decimal.valueOf(valueLat);
    decimal topLat = 0.0015 + Decimal.valueOf(valueLat);
    decimal bottomLong = -0.0015 + Decimal.valueOf(valueLong);
    decimal topLong = 0.0015 + Decimal.valueOf(valueLong);
    system.debug('bottomLat == ' + bottomLat  );
    system.debug('topLat == ' + topLat);
    system.debug('topLong == ' + topLong);
    system.debug('bottomLong == ' + bottomLong);
    nearbyStops = [Select Id, Latitude__c, Longitude__c, StopId__c from CTA_Stop_Location__c where (Latitude__c > :bottomLat and Latitude__c < :topLat) and (Longitude__c > :bottomLong and Longitude__c < :topLong)];
     set<String> ids = new set<String>();
     for(CTA_Stop_Location__c stopLoc : nearbyStops)
    for(String id : ids)
        String xmlPredictionsResponse = getBusPredictions(id);
        List<BusPrediction> tempPredicts = foundBusPredictions(xmlPredictionsResponse);
     return null;


Cory CowgillCory Cowgill

Also - you should look at FindNearby on AppExchange. If you go to the Force.com Labs boards you can request source code for the application which will show you how to use Google GeoCoding service /  Force.com to add Lat/Long values to your objects in SF based on addresses.