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
Sugandhi VermaSugandhi Verma 

not getting the gmap on visualforce page


Hii, I have a page and class.I have the field location of geolocation type.I want to show the location on GMAP when i search for a particular thing.Like when i select 'India', i am getting the records of having address in India But not getting their location on GMAP. My code is: 
Page:
 <apex:page controller="tourmapController1" tabStyle="Accomodation__c" action="{!find}" id="page">  
  <head>      
  <style>       
      div #map_canvas { height: 400px; }      
  </style>     
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>  
  </head>   
  <apex:sectionHeader title="Hello StackOverflow!" subtitle="Accomodation full text search + Google Maps integration" />  
  <apex:pageMessages /> 
    <apex:form id="form">       
  <apex:pageBlock id="searchBlock">       
      <apex:inputText value="{!searchText}" />    
        <apex:commandButton value="Search" action="{!find}"/>    
        <p>Examples: <a href="/apex/{!$CurrentPage.Name}?q=USA">"USA"</a>, "Singapore", "Uni", "(336) 222-7000". If it works in the global search box, it will work here.</p>    
    </apex:pageBlock>     
    <apex:pageBlock title="Found {!accod.size} Accomodation__c..." rendered="{!NOT(ISNULL(accod)) && accod.size > 0}" id="resultsBlock">             <apex:pageBlockButtons location="top">    
            <apex:commandButton value="Clear cached locations" title="Click if you want to set 'null' as geolocation info for all these accomodations" action="{!clearGeocodedData}" />   
          </apex:pageBlockButtons>        
    <apex:pageBlockTable value="{!accod}" var="a" id="accod">    
            <apex:column headerValue="{!$ObjectType.Accomodation__c.fields.Name.label}">         
            <apex:outputLink value="../{!a.Id}">{!a.Name}</apex:outputLink>    
            </apex:column>                 
<apex:column headerValue="Address">           
          {!a.Street_Address__c} {!a.City__c} {!a.Country__c}      
          </apex:column>               
  <apex:column value="{!a.Accomodation_Name__c}"/>             
    <apex:column headerValue="Location (retrieved from DB or geocoded server-side)">       
              {!a.Location__Latitude__s}, {!a.Location__Longitude__s}           
      </apex:column>            
</apex:pageBlockTable>           
  <apex:pageBlockSection columns="1" id="mapSection">       
          <div id="map_canvas" />         
    </apex:pageBlockSection>            
<apex:pageBlockSection title="Click to show/hide what was geocoded server-side and passed to JS for further manipulation" columns="1" id="debugSection">       
         1 {!debugAccomodationJson}        
    </apex:pageBlockSection>            1      
    </apex:pageBlock>   
  </apex:form>    
<script type="text/javascript">   
  twistSection(document.getElementById('page:form:resultsBlock:debugSection').childNodes[0].childNodes[0]); // initially hide the debug section     var accod = {!accodJson};  
      var coords = [];                
    var requestCounter = 0;    
var markers = [];                  // Red things we pin to the map.  
  var balloon = new google.maps.InfoWindow();   
  function geocodeClientSide() {    
    for(var i = 0; i < accod.length; i++) {       
      if(accod[i].Location__Latitude__s != null && accod[i].Location__Longitude__s != null) {     
            coords.push(new google.maps.LatLng(accod[i].Location__Latitude__s, accod[i].Location__Longitude__s));      
      } 
else {             
    ++requestCounter;              
  var address = accod[i].Street_Address__c + ' ' + accod[i].City__c + ' ' + accod[i].Country__c;    
            var geocoder = new google.maps.Geocoder();    
            if (geocoder) {        
            geocoder.geocode({'address':address},
function (results, status) {        
                if (status == google.maps.GeocoderStatus.OK) {         
                    coords.push(results[0].geometry.location);            
            } 
else {                          
  var pTag = document.createElement("p");           
                  pTag.innerHTML = status;            
                document.getElementById('log').appendChild(pTag);       
                  }                      
  if(--requestCounter == 0) {                     
        drawMap();                
        }              
      });            
    }       
      }    
    }            
    if(requestCounter == 0) {      
      drawMap();     
    }   
  }    
function drawMap(){  
      var mapOptions = {        center: coords[0],            zoom: 3,             mapTypeId: google.maps.MapTypeId.ROADMAP         };   
     var map = new google.maps.Map(document.getElementById("map_canvas"),  mapOptions);   
      for(var i = 0; i < coords.length; ++i){      
      var marker = new google.maps.Marker({map: map, position: coords[i], title:accod[i].Name, zIndex:i});    
        google.maps.event.addListener(marker, 'click', function() {            
    var index = this.zIndex;               
  balloon.content = '<b>'+accod[index].Name + '</b><br/>' + accod[index].Accomodation_Name__c + '<br/>' + accod[index].City__c;                 balloon.open(map,this);    
        });      
      markers.push(marker);    
    }   
  }   
  geocodeClientSide();   
  </script> 
</apex:page> 


Class: 
public with sharing class tourmapController1 {  
  public String accodJson { get; set; }  
public String searchText {get;set;}
public List<Accomodation__c> accod{get; private set;}
public static final String GEOCODING_URI_BASE = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=true&address='; 
public static final Integer MAX_CALLOUTS_FROM_APEX = 3; // Limits.getLimitCallouts() 
public tourmapController1(){     
searchText = ApexPages.currentPage().getParameters().get('q'); 

public void find() {   
  if(searchText != null && searchText.length() > 1){     
    List<List<SObject>> results = [FIND :('*' + searchText + '*') IN ALL FIELDS RETURNING              Accomodation__c (Id, Name,Accomodation_Name__c,                 Street_Address__c,City__c,PostalCode__c, State__c, Country__c,                  Location__Latitude__s, Location__Longitude__s)             ];   
      accod = (List<Accomodation__c>)results[0];    
    if(accod.isEmpty()){       
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'No matches for "' + searchText + '"'));   
      } 
else {       
      serverSideGeocode();      
  }   
  } 
else {   
      if(accod != null) {       
      accod.clear();     
    }        
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Please provide at least 2 characters for the search.'));  
  } } 
public void clearGeocodedData(){ 
    for(Accomodation__c a : accod){     
    a.Location__Latitude__s = a.Location__Longitude__s = null;  
  }    
Database.update(accod, false);     
accod.clear(); 

public String getAccomodationJson(){  
  return JSON.serialize(accod);

public String getDebugAccomodationJson(){ 
    return JSON.serializePretty(accod); 

private void serverSideGeocode(){  
  List<Accomodation__c> accodToUpdate = new List<Accomodation__c>();   
  Http h = new Http();  
    HttpRequest req = new HttpRequest(); 
    req.setMethod('GET');    
  req.setTimeout(10000);  
  for(Accomodation__c a : accod){  
      if((a.Location__Latitude__s == null || a.Location__Longitude__s == null)){     
        String address = a.Street_Address__c != null ? a.Street_Address__c + ' ' : '' +                 a.City__c != null ? a.City__c + ' ' : '' +                 a.State__c != null ? a.State__c + ' ' : '' +                 a.PostalCode__c != null ? a.PostalCode__c + ' ' : '' +                 a.Country__c != null ? a.Country__c : '';    
        if(address != ''){        
        req.setEndpoint(GEOCODING_URI_BASE + EncodingUtil.urlEncode(address, 'UTF-8'));         
        try{      
              HttpResponse res = h.send(req);               
      GResponse gr = (GResponse) JSON.deserialize(res.getBody(), tourmapController1.GResponse.class);  
                  if(gr.status == 'OK'){       
                  LatLng ll = gr.results[0].geometry.location;            
            a.Location__Latitude__s = ll.lat;             
            a.Location__Longitude__s = ll.lng;       
                  accodToUpdate.add(a);          
          } 
else {            
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Geocoding of "' + address + '" failed:' + gr.status));  
                  }          
      }
catch(Exception e){       
              ApexPages.addMessages(e);      
          }      
      }                
          if(Limits.getCallouts() == MAX_CALLOUTS_FROM_APEX) {            
    break;         
    }     
    }   
  }   
  if(!accodToUpdate.isEmpty()) {  
      Database.update(accodToUpdate, false); // some data in Developer editions is invalid (on purpose I think).        

  } }
public class GResponse{   
  public String status; 
    public GComponents[] results;

public class GComponents{    
public String formatted_address;  
 public GGeometry geometry; 

public class GGeometry {   
  public LatLng location; 

public class LatLng{  
  public Double lat, lng;
}
​ }
sandeep sankhlasandeep sankhla
Hi Sugnadhi,

Please refer the below link for help..
http://salesforceapexcodecorner.blogspot.in/2012/06/multiple-address-on-visualforce-page.html

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Thanks,
Sandeep
Salesforce Certified Developer 
Sugandhi VermaSugandhi Verma
Hi sandeep,
http://salesforceapexcodecorner.blogspot.in/2012/06/multiple-address-on-visualforce-page.html
It's not working accurately.I also want to add the functionality of calculating distance and time.