function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Suhail AyubSuhail Ayub 

Need help regarding geolocation salesforce !

So while I was working with geolocations and formula fields I found that there is a function "GEOLOCATION(latitude, longitude)-Returns a location based on the provided latitude and longitude.​"  

I wanted to know if there is anything that does the reverse of this i.e. takes the location/address and returns me the lattitude and longitude. 

If not, Is there any way to do it ? 

Thanks,

Suhail Ayub

Girija Joshi 14Girija Joshi 14
Hi Suhail,

You can use request google "http://maps.googleapis.com/maps/api/geocode/js?v=3&sensor=false". 

var geoinfo = new google.maps.Geocoder();
var geocoderRequest = {
address: address
}

geoinfo.geocode(geocoderRequest, function(results, status)

now if status is OK then you will have information init like :

"results" : [
      {
         "address_components" : [
            {
               "long_name" : "South Federal Street",
               "short_name" : "S Federal St",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Chicago",
               "short_name" : "Chicago",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Cook County",
               "short_name" : "Cook County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Illinois",
               "short_name" : "IL",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "S Federal St, Chicago, IL, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 41.8781499,
                  "lng" : -87.62806429999999
               },
               "southwest" : {
                  "lat" : 41.8351969,
                  "lng" : -87.6305809
               }
            },
            "location" : {
               "lat" : 41.8565851,
               "lng" : -87.6294257
            },
            "location_type" : "GEOMETRIC_CENTER",
            "viewport" : {
               "northeast" : {
                  "lat" : 41.8781499,
                  "lng" : -87.6279736197085
               },
               "southwest" : {
                  "lat" : 41.8351969,
                  "lng" : -87.63067158029151
               }
            }
         },
         "partial_match" : true,
         "place_id" : "ChIJ_75fWm0sDogR-TX83SoXAq0",
         "types" : [ "route" ]
      }
   ],
   "status" : "OK"

now you can get the logitude and latitude:
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
 
Suhail AyubSuhail Ayub

Hey! thanks a lot for this.I need more clarification on this. 

var geoinfo = new google.maps.Geocoder();
var geocoderRequest = {
address: address
}

geoinfo.geocode(geocoderRequest, function(results, status)

So, you mean the address part in the code should be the address i am searching for ? 

for instance, 

var geoinfo = new google.maps.Geocoder();
var geocoderRequest = {
address: Bangalore-560087
}

geoinfo.geocode(geocoderRequest, function(results, status)

is this right ? 

Girija Joshi 14Girija Joshi 14
yes address what you are trying to search, is the location i will have something like:

var address = 'Bangalore'.

Hope it helps.
Girija Joshi 14Girija Joshi 14
Suhail,

did you get what you were trying to do? If not then i have simple class basic class check and see if it usefull for you or not.
Suhail AyubSuhail Ayub

Hi Girija , 

I am still stuck up with this , can you show me the class that you are talking about ?
 

thanks 

Girija Joshi 14Girija Joshi 14
here you go. its very dirty, but from account object i take billing city from that I get Latitude and Longitude from google then I update Latitude and Longitude field values in account.
You need to do couple of things:
1) Remote Site Settings:  add  'https://maps.googleapis.com'
2) Go to Google credential and generate auth key so that you can use that key in https request


public class TryMap {

    public static Map<ID, String> MapOfIDAndCity = new Map<ID, String>();
    public static Map<ID, LIST<Decimal>> MapOfIDAndLonLat =  new Map<ID, LIST<Decimal>>();
    
    public static void GetAccInfoFromAcc() {
    
        
        List<Decimal> LonAndLat;        
        List<Account> AccInfo = [SELECT id,BillingCity FROM Account LIMIT 2];
      
        //iterate through and find out the only not not empty cities
        for (integer i = 0; i < AccInfo.size(); i++ ) {
            if(!(String.isEmpty(AccInfo.get(i).BillingCity))) {
                // store the account id and billing sity in map
                TryMap.MapOfIDAndCity.put(AccInfo.get(i).id,AccInfo.get(i).BillingCity);               
            }
        }
        
        //Now i wll have pair of id and city not get lan and latitude for this city
       
        for ( ID aID: TryMap.MapOfIDAndCity.keySet() ) {            
            String address = TryMap.MapOfIDAndCity.get(aID);
                       
            //********************************************************* //
            address = EncodingUtil.urlEncode(address, 'UTF-8');
            // build http call out
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            //Key_AUTH is here my auth key i generated in google credentials.
            req.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?key=<Key_Auth>&address='+address+'&sensor=false');           
            req.setMethod('GET');
            req.setTimeout(6000);
            
            try{
               // callout
               HttpResponse res = h.send(req);               
               JSONParser parser = JSON.createParser(res.getBody());
               double lat = null;
               double lon = null;
               integer cnt = 0;
               while (parser.nextToken() != null) {
                   
                   if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'location')) {                    
                      LonAndLat = new List<Decimal>();                    
                      parser.nextToken(); // object start
                      while (parser.nextToken() != JSONToken.END_OBJECT){
                           String txt = parser.getText();                           
                           parser.nextToken();                           
                           
                           if (txt == 'lat') {
                               lat = parser.getDoubleValue();
                               //system.debug('== LAT ===='+ aID + ' LAT: ' + lat);
                               if(cnt == 0) {
                                   LonAndLat.add(lat);
                               }
                               cnt = cnt + 1;
                               
                           }
                           else if (txt == 'lng') {
                               lon = parser.getDoubleValue();
                               //system.debug('== LON ====' + aID + ' LON: ' + lon);
                               if(cnt == 1) {
                                   LonAndLat.add(lon);
                               }
                               cnt = cnt + 1;
                           }
                                                      
                       } // while
                       if(!LonAndLat.isEmpty()) {
                               //Add to list
                               //system.debug('========= PUTTING VAL aID ====' + aID + ' pos ' + LonAndLat);
                               TryMap.MapOfIDAndLonLat.put(aID,LonAndLat);                                                         
                       }                                                                 
                   } //if
                                      
               }// while                              
            } // try
            catch( Exception e) {
                 system.debug('== Exception Occured ====' + e.getMessage());
            } 
            
            //TryMap.MapOfIDAndLonLat1 = MapOfIDAndLonLat;           
        } //for
        
       
    } //function
    
    public static void UpdateAccInfoLonAndLat() {
        List<Account> AccInfo = [SELECT id, BillingCity , Latitude__c, Longitude__c FROM Account LIMIT 2];       
        List<Account> finalAcc = new List<Account>();
        
         for(Account acc:AccInfo ) {
             //if accid is in maplist then change update the longitude and latitude
             for ( ID aID: TryMap.MapOfIDAndLonLat.keySet() ) {
                 if(acc.ID == aID) {
                     List<Decimal> tmp = TryMap.MapOfIDAndLonLat.get(aID);
                     acc.Latitude__c = tmp.get(0);
                     acc.Longitude__c= tmp.get(1);
                     //System.debug('======== ADD ID: ' + aID + ' Lat: ' +  acc.Latitude__c + ' Lon: ' + acc.Longitude__c);
                     finalAcc.add(acc);
                 }
             } //for id
         } //for
         
          if(!finalAcc.isEmpty()) {
             System.debug('====== FINAL ACC IS NOT EMPTY ============' + finalAcc );
             update finalAcc;
        }
    }
    
} //class
Girija Joshi 14Girija Joshi 14
let me know if it was helpful for you not.