+ Start a Discussion
BJMBJM 

Display All Contacts and Leads on Google Maps using Visualforce and Apex

Hi all ,
          I have a requirement that i need to to display all Contacts and Leads of our Organization on Google maps using Single Visualforce page to track All Contacts and Leads from Current Location, Here i displayed all Leads from current location but i need to display All Contacts also for the same Page if any one knows pls help

Here is my code

Class:
--------
global with sharing class LeadsNearbyMe {

public Lead leads{get; set;}

@RemoteAction
   global static List<Lead> getNearby(String lat, String lon) {

        if(lat == null || lon == null || lat.equals('') || lon.equals('')) {
            lat = '51.096214';
            lon = '3.683153';
        }

        String queryString =
            'SELECT Id, Name, Location__Longitude__s, Location__Latitude__s, ' +
                'Street, City,State,Country, PostalCode ' +
            'FROM Lead ' +
            'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') < 60 ' +
            'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') ' +
            'LIMIT 25';
        return(database.Query(queryString));
    }
}

Page:
--------

<apex:page sidebar="false" showheader="false" controller="LeadsNearbyMe">
 
  <apex:includeScript value="{!$Resource.googleMapsAPI}" />
      <script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCROH4OR9fzDhmprWPL1wGWfPT4uGUeMWg&sensor=false">
        </script>
        
    <!-- Setup the map to take up the whole window -->
    <style>
        html, body { height: 100%; }
        .page-map, .ui-content, #map-canvas { width: 100%; height:100%; padding: 0; }
        #map-canvas { height: min-height: 100%; }
    </style>
    
    <script>
        function initialize() {
            var lat, lon;
          
             if (navigator.geolocation) {
                 navigator.geolocation.getCurrentPosition(function(position){
                     lat = position.coords.latitude;
                     lon = position.coords.longitude;                    
                     
                     // Use Visualforce JavaScript Remoting to query for nearby conts      
                     Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.LeadsNearbyMe.getNearby}', lat, lon,
                         function(result, event){
                             if (event.status) {
                                 console.log(result);
                                 createMap(lat, lon, result);           
                             } else if (event.type === 'exception') {
                                 //exception case code          
                             } else {
                                            
                             }
                          },
                          {escape: true}
                      );
                  });
              } else {
                  // Set default values for map if the device doesn't have geolocation capabilities
                    /** Eindhoven **/
                    lat = 51.096214;
                    lon = 3.683153;
                    
                    var result = [];
                    createMap(lat, lon, result);
              }
          
         }
    
         function createMap(lat, lon, leads){
            var currentPosition = new google.maps.LatLng(lat,lon);
            var mapDiv = document.getElementById('map-canvas');
            var map = new google.maps.Map(mapDiv, {
                center: currentPosition,
                zoom: 13,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            
            // Set a marker for the current location
            var positionMarker = new google.maps.Marker({
                map: map,
                position: currentPosition,
                title: 'You are here',
            });
            
            // Keep track of the map boundary that holds all markers
            var mapBoundary = new google.maps.LatLngBounds();
            mapBoundary.extend(currentPosition);
            
            // Set markers on the map from the @RemoteAction results
            var cont;
            for(var i=0; i<leads.length;i++){
                cont = leads[i];
                console.log(leads[i]);
                setupMarker();
            }
       map.fitBounds(mapBoundary);

           function setupMarker(){
                var contNavUrl;
           
                try{
                    if(sforce.one){
                        contNavUrl =
                            'javascript:sforce.one.navigateToSObject(\'' + cont.Id + '\')';
                    }
                } catch(err) {
                    console.log(err);
                    contNavUrl = '\\' + cont.Id;
                }
                
                var contDetails =
                    
                    cont.Name + ',' +
                    cont.Street + ',' +
                    cont.City + ',' +
                    cont.PostalCode;
           var marker = new google.maps.Marker({
                   map: map,
                   icon : "{!URLFOR($Resource.GoogleMarkers, 'GoogleMark/4-l.png')}",
                   title:contDetails,
                   position: new google.maps.LatLng(
                                   cont.Location__Latitude__s,
                                   cont.Location__Longitude__s)
               });
               mapBoundary.extend(marker.getPosition());
           }
                  
           }
 
        google.maps.event.addDomListener(window, 'load', initialize);
        
    </script>
<body style="font-family: Arial; border: 0 none;">
 
        <div id="map-canvas"></div>
    </body>
 
</apex:page>


Screen shot:
------------------

User-added image


Thanks & Regards,
Iqrar AhmedIqrar Ahmed
Hi Bjm,

You can do this by store queried data of contact and lead in wrapper class .Create a single method for fetching contact and Lead information that will return wrapper class in your remote controller 

@RemoteAction
   global static List<Wrapper> getNearby(String lat, String lon) {
   
         wrapper wp=new wrapper();
        if(lat == null || lon == null || lat.equals('') || lon.equals('')) {
            lat = '51.096214';
            lon = '3.683153';
        }

        String queryString =
            'SELECT Id, Name, Location__Longitude__s, Location__Latitude__s, ' +
                'Street, City,State,Country, PostalCode ' +
            'FROM Lead ' +
            'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') < 60 ' +
            'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') ' +
            'LIMIT 25';

          String queryString2 =
            'SELECT Id, Name, Location__Longitude__s, Location__Latitude__s, ' +
                'Street, City,State,Country, PostalCode ' +
            'FROM Contact ' +
            'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') < 60 ' +
            'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') ' +
            'LIMIT 25';
      /*
      create a logic here to add both contact data and lead data in wrapper class
     */
    return wp;
}

Best Regards
IQRAR AHMED
Senior Salesforce/.Net developer
Ramakrishnan AyyanarRamakrishnan Ayyanar
can you share this  static resource file Resource.googleMapsAPI?
I need to go check for this mapping .

 
Ramakrishnan AyyanarRamakrishnan Ayyanar

global with sharing class LeadsNearbyMe
{


global class WrapperHelper
{
global string Name {get;set;}
//add your required properties here
}

public Lead leads{get; set;}

@RemoteAction
   global static List<WrapperHelper> getNearby(String lat, String lon)
  {

      List<WrapperHelper> WrapperHelperList=new List<WrapperHelper>();

        if(lat == null || lon == null || lat.equals('') || lon.equals(''))
       {
            lat = '51.096214';
            lon = '3.683153';
        }

        String queryStringLead =
            'SELECT Id, Name, Location__Longitude__s, Location__Latitude__s, ' +
                'Street, City,State,Country, PostalCode ' +
            'FROM Lead ' +
            'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') < 60 ' +
            'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') ' +
            'LIMIT 25';
        List<Lead> LeadList= database.Query(queryStringLead);


  String queryStringContact =
            'SELECT Id, Name, Location__Longitude__s, Location__Latitude__s, ' +
                'Street, City,State,Country, PostalCode ' +
            'FROM Contact ' +
            'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') < 60 ' +
            'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'km\') ' +
            'LIMIT 25';

List<Contact> ContactList= database.Query(queryStringContact);

//add sample logic here
for(Lead lead:LeadList)
{
WrapperHelper wrapper=new WrapperHelper();
wrapper.Name=lead.name;

WrapperHelperList.add(wrapper);
}

for(Contact con:ContactList)
{
WrapperHelper wrapper=new WrapperHelper();
wrapper.Name=con.name;

WrapperHelperList.add(wrapper);
}

return WrapperHelperList;
    }
}
shobana shobanashobana shobana
Hi BJM

Can you please share the static resource file GoogleMarkers,googleMapsAPI

Thank you in advance.
BJMBJM
Hi shobana,
could you check this url:  http://sfdchack.blogspot.in/2012/10/adding-multiple-different-colour-marker.html
I used 4-I markers for Leads and 3-c markers for Contacts from the zip file for my page

Thanks and regards ...!
BJMBJM
Hi shobana,
the above reply is reference for markers 
could you check this url:  https://dl.dropboxusercontent.com/u/29695913/GoogleMarkers.zip 
the markers zip file will downloaded
I used 4-I marker for Leads and 3-c marker for Contacts from the zip file for my page

Thanks ...!

 
shobana shobanashobana shobana
Hi BJM,

Thank you for your reply i will check now....
shobana shobanashobana shobana
Hi BJM,
I tried your code but it showing blank space.
Can you help me out to solve this issue..
Thank you in advance..
yogesh_sharmayogesh_sharma
Hi BJM,
Can you please provide me static resource file for googleMapsApi.
Thanks in Advance!:)
d.tejdeep@nicomatic.ind.tejdeep@nicomatic.in
Hi 

I am looking for the same can you anybody share code completely ?

the above code showing blank page 
Thanks
Harsimran Singh BawejaHarsimran Singh Baweja
I am getting error " Error: Unknown property 'String.googleMapsAPI". Can anyone share the static resource file please also the full code?