Salesforce Google Map Integration

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/”.

Account Tracker Proposal (1)

                                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.

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.

 

  1.  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:

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:

https://developers.google.com/maps/documentation/geocoding/start

Google Apis Authentication by passing the Access Key:

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);

Account Tracker Proposal

  1. 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:

Distance and Path calculation between Starting and End Point:

function calcRoute() {

 var start = document.getElementById(‘start’).value;

 var end = document.getElementById(‘end’).value;

 var waypts = [];

 var checkboxArray = document.getElementById(‘waypoints’);

 for (var i = 0; i < checkboxArray.length; i++) {

   if (checkboxArray.options[i].selected == true) {

     waypts.push({

         location:checkboxArray[i].value,

         stopover:true});

   }

 }

 

 var request = {

     origin: start,

     destination: end,

     waypoints: waypts,

     optimizeWaypoints: true,

     travelMode: google.maps.TravelMode.DRIVING

 };

 directionsService.route(request, function(response, status) {

   if (status == google.maps.DirectionsStatus.OK) {

     directionsDisplay.setDirections(response);

     var route = response.routes[0];

     var summaryPanel = document.getElementById(‘directions_panel’);

     summaryPanel.innerHTML = ”;

     

     // For each route, display summary information.

     for (var i = 0; i < route.legs.length; i++) {

       var routeSegment = i + 1;

       summaryPanel.innerHTML += ‘<b>Route Segment: ‘ + routeSegment + ‘</b><br/>’;

       summaryPanel.innerHTML += route.legs[i].start_address + ‘ to ‘;

       summaryPanel.innerHTML += route.legs[i].end_address + ‘<br/>’;

       summaryPanel.innerHTML += route.legs[i].distance.text + ‘<br/><br/>’;

     }

   }

 });

}

 

                                               function returnCity(){

                                                               //lat = position.coords.latitude;

                                         //lon = position.coords.longitude;

                                               var geocoder1;

                                               geocoder1 = new google.maps.Geocoder();

                                               console.log(lat+’—-‘+lon);

                                               var latlng1 = new google.maps.LatLng(lat, lon);

                                                geocoder1.geocode(

                                                        {‘latLng’: latlng1},

                                                        function(results, status) {

                                                           if (status == google.maps.GeocoderStatus.OK) {

                                                              if (results[0]) {

                                                                  var add= results[0].formatted_address ;

                                                                  var  value=add.split(“,”);

                                                                  count=value.length;

                                                                  country=value[count-1];

                                                                  state=value[count-2];

                                                                  city=value[count-3];

                                                                  cityName = city;

                                                                  var optionNode = document.createElement(“option”);

                                                                  optionNode.innerHTML = ‘My Location’;

                                                                  optionNode.setAttribute(‘value’, cityName);

                                                                  optionNode.setAttribute(‘selected’, ‘selected’);

                                                                  document.getElementById(‘start’).appendChild(optionNode);

                   

                                                                  var optionNode1 = document.createElement(“option”);

                                                                  optionNode1.innerHTML = ‘My Location’;

                                                                  optionNode1.setAttribute(‘value’, cityName);

                                                                  //optionNode.setAttribute(‘selected’, ‘selected’);

                                                                  document.getElementById(‘end’).appendChild(optionNode1);

                                                                  alert(“city name is: ” + city);

                                                                   console.log(‘***city–‘+city);

                   

               }

               else  {

                   alert(“address not found”);

               }

       }

        else {

           alert(“Geocoder failed due to: ” + status);

       }

   }

);

return cityName;

console.log(‘***cityName–‘+cityName);

console.log(‘***city–>>’+city);

}

 

google.maps.event.addDomListener(window, ‘load’, initialize);

 

function cityLocal(){

returnCity();

//console.log(‘***cityName–‘+cityName);

}

   </script>

 </head>

 <body>

   <div id=”map-canvas” style=”float:left;width:70%;height:100%;”></div>

    <script>

           getLocation();

           //returnCity();

       </script>

   

      

   <div id=”control_panel” style=”float:right;width:30%;text-align:left;padding-top:20px”>

   <div style=”margin:20px;border-width:2px;”>

   <b>Start:</b>

   <select id=”start” >

     <option value=”Kerala, KL”>Kerala, KL</option>

     <option value=”Maharashtra, MH”>Maharashtra, MH</option>

     <option value=”Tamil Nadu, TN”>Tamil Nadu, TN</option>

   </select>

   <br/>

   <apex:form >

       <apex:actionFunction name=”setValue”>

        <apex:param name=”x” value=”x” assignTo=”{!selectdAcc}”/>

    </apex:actionFunction>

   <b>Waypoints:</b> <br/>

   <i>(Ctrl-Click for multiple selection)</i> <br/>

   <select multiple=”true” id=”waypoints” onselect=”setValue(this.value)”>

 <option value=””>–None–</option>

 <apex:repeat value=”{!Accts}” var=”Acc”>

       <option value=”{!Acc.BillingCity}”>

        {!Acc.Name}

       </option>

     </apex:repeat>

</select>

</apex:form>

   <br/>

   <b>End:</b>

   <select id=”end”>

     <option value=”Goa, GA”>Goa, GA</option>

     <option value=”Gujarat, GJ”>Gujarat, GJ</option>

     <option value=”Haryana, HR”>Haryana, HR</option>

     <option value=”Himachal Pradesh, HP”>Himachal Pradesh, HP</option>

   </select>

   <br/>

     <input type=”submit” onclick=”calcRoute();”/>

   </div>

   <div id=”directions_panel” style=”margin:20px;background-color:#FFEE77;”></div>

   </div>

This Code will get User’s location from browser on load of the page and it will be stored in Start as “My location”. See below:

Maps

For Directions services we used “directionsService.route(request, function(response, status) { }” function.

Author: AJ

Share This Post On

2 Comments

  1. Great one sir…..

    Post a Reply
  2. Nice script but please share the code in singel flow

    Post a Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

× How can I help you?