Friday, September 9, 2016


Google Map Integration

Integrating google maps into Salesforce
Description of the requirement:
Starting with description of the Project we have worked upon, there’s an app we created for searching and showing Account’s location on the Map and knowing a route map from one location to another location via some locations(Checkpoints).

Solution we came with:
For the requirement we used Google maps api which is in Javascript format. There are some predefined javascript functions used in the Google map api. We used Google Maps library whoz source is coming from a link i.e., “https://maps.google.com/maps/api/”.



There are several Javascript functions we used here which are as follows:

  1. Function to get the current location of the User by using the browser’s location.

var geocoder;
           var map;
           function initialize(){
               geocoder = new google.maps.Geocoder();    
               console.log(lon+'***latlon--'+lat );
               var latlng = new google.maps.LatLng(lat, lon);
               console.log('***latlon--'+latlng);
               var myOptions = {
                 zoom: 12,
                 center: latlng,
                 mapTypeId: 'roadmap' /* ,
                 mapTypeId: google.maps.MapTypeId.TERRAIN */
               }                         
               map = new google.maps.Map(document.getElementById("map"), myOptions);
 

Here we used “google.maps.Geocoder();” to access Google Maps API geocoding service.

2.  We created an apex class method which will take Address of the Account as a string and will return a Geolocation for that address i.e., in Latitude and longitude of the string  address passed in the function as a parameter to it.  

Suppose a string will be as shown below:
public Account accObj{get;set;} // This is a getter setter method contains Account record.
String address = accObj.BillingStreet+accObj.BillingCity+accObj.BillingPostalCode+accObj.BillingCountry;


Now we used the below method to get the Latitude & Longitude:

public static String getLatitudeLongitude(String address){
       String location='';
        try{
               Double latitude = null;
               Double longitude = null;
           
               Http httpGetRequest = new Http();
               HttpRequest httpReq = new HttpRequest();
               system.debug('******Address---'+address);
               address=address.replaceAll(' ','+');
               address = address.replace('\r\n', ' ');
                       address = address.replace('\n', ' ');
                       address = address.replace('\r', ' ');
                       system.debug('******After       Address---'+address);
                       httpReq.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?key='+key+'&address=' +address + '&sensor=false'); //Authentication to google api
           httpReq.setMethod('GET');
           httpReq.setTimeout(6000);
           HttpResponse httpResponseAddress = httpGetRequest.send(httpReq);
               system.debug('res body: ' + httpResponseAddress.getBody());
               JSONParser parser = JSON.createParser(httpResponseAddress.getBody());
           
           
           while (parser.nextToken() != null)
           {
               if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'location'))
                   {
                      // Jump to latitude and longtitude fields.
                       parser.nextToken();

                       while (parser.nextToken() != JSONToken.END_OBJECT)
                       {
                           String text = parser.getText();
                           parser.nextToken();
                           if (text == 'lat') latitude = parser.getDoubleValue();
                           else if (text == 'lng') longitude = parser.getDoubleValue();
                       }
                   }
           }

           // Update Account coordinates.
           if (latitude != null)
           {
               location+= latitude + ', ' +  longitude;               
           }
           
           
       }catch(Exception e){
               system.debug('***** Exception Occured '+e.getMessage());
       }
       return location;
   }



In this method, we passed address string as the parameter and then that string will be used to be converted into a geolocation.

We also did authentication for Google Apis in this method by passing the Access Key like this:

Storing Key in a separate variable:
You can get your access key from here:

httpReq.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?key='+key+'&address=' +address + '&sensor=false');
httpReq.setMethod('GET');
httpReq.setTimeout(6000);
HttpResponse httpResponseAddress = httpGetRequest.send(httpReq);



3. We created something to Calculate and show the distance and path between a Starting Point - Waypoints(Via) - Endpoint.
For this we used Google Api’s Directions Service.

The Code and explanation is given below: