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., “”.

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


               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 =



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

Get the Latitude & Longitude:

public static String getLatitudeLongitude(String address){

       String location=”;


               Double latitude = null;

               Double longitude = null;


               Http httpGetRequest = new Http();

               HttpRequest httpReq = new HttpRequest();


               address=address.replaceAll(‘ ‘,’+’);

               address = address.replace(‘\r\n’, ‘ ‘);

                       address = address.replace(‘\n’, ‘ ‘);

                       address = address.replace(‘\r’, ‘ ‘);

                       system.debug(‘******After       Address—‘+address);

      httpReq.setEndpoint(‘’+key+’&address=’ +address + ‘&sensor=false’);                                                                                            //Authentication to google api



           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.



                       while (parser.nextToken() != JSONToken.END_OBJECT)


                           String text = parser.getText();


                           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:

Google Apis Authentication by passing the Access Key:

httpReq.setEndpoint(‘’+key+’&address=’ +address + ‘&sensor=false’);



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







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


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


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


                                                        {‘latLng’: latlng1},

                                                        function(results, status) {

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

                                                              if (results[0]) {

                                                                  var add= results[0].formatted_address ;

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





                                                                  cityName = city;

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

                                                                  optionNode.innerHTML = ‘My Location’;

                                                                  optionNode.setAttribute(‘value’, cityName);

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



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

                                                                  optionNode1.innerHTML = ‘My Location’;

                                                                  optionNode1.setAttribute(‘value’, cityName);

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


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




               else  {

                   alert(“address not found”);



        else {

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




return cityName;





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


function cityLocal(){







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







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

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


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



   <apex:form >

       <apex:actionFunction name=”setValue”>

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


   <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}”>








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



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


   <div id=”directions_panel” style=”margin:20px;background-color:#FFEE77;”></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:


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

Author: AJ

Share This Post On


  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.

× How can I help you?