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
Reshmi SmijuReshmi Smiju 

Issues while passing values from Apex Class to VF Page.

Hi ,

I have come across some trouble with my code. I need to pass some list of values to VF page from My Class. My code is below.
In this, I am marking some latitude + longitude  on the google Map.  locations is coming from the Apex Class.
Along with location ,  I need to pull contacts details +mailing Address to show them in the small window in map. I know, the expression  !contacts.Name , is wrong. How to correct my code. Pls advise.

PAGE CODE
<apex:pageBlockSection rendered="{!resultsAvailable}" title="Locations">
            <apex:map width="600px" height="400px">
                <apex:repeat value="{!locations}" var="pos">
                    <apex:mapMarker position="{!pos}">
                        <!-- Add info window with contact details -->
                        <apex:mapInfoWindow >
                        <apex:outputPanel layout="block" style="font-weight: bold;">
                            <apex:outputText>{!contacts.Name }</apex:outputText>
                        </apex:outputPanel>
                      </apex:mapInfoWindow>
                    </apex:mapMarker>
                </apex:repeat>

            </apex:map>
        </apex:pageBlockSection>

APEX CLASS CODE

 String queryString =            'SELECT Id, Name, MailingStreet, MailingCity, MailingState, Phone, Location__longitude__s, Location__latitude__s ' +            'FROM Contact ' +            'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') < 20 ' +            'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') ' +            'LIMIT 10';         System.Debug('>>>> the value of queryString is ' + queryString);
        // Run the query         
List <Contact> contacts = database.query(queryString);         
if(contacts.size() > 0 ) {             
// Convert to locations that can be mapped             
locations = new List<Map<String,Double>>();       
      for (Contact con : contacts) {                 
locations.add( new Map<String,Double>{                         
'latitude' => con.Location__latitude__s,                          
'longitude' => con.Location__longitude__s                     
}                 
);             
}         
}         
else {             
System.debug('No results. Query: ' + queryString);         
}

Thanks much in Advance.
Reshmi
Best Answer chosen by Reshmi Smiju
hitesh90hitesh90
Hello Reshmi,

There are some mistake in the existing code. please try to use below code.

Apex Class:
public with sharing class FindNearbyController{
    public List<Contact> contacts{ get; private set; }
    public String currentPosition { 
        get {
            if (String.isBlank(currentPosition)) {
                currentPosition = '37.77493,-122.419416'; // San Francisco
            }
            return currentPosition;
        }
        set; 
    }    
    public Boolean resultsAvailable {
        get {
            if(contacts == Null) {
                return false;
            }
            return true;
        }
    }
    
    public PageReference findNearby() {
        String lat, lon;
        
        // FRAGILE: You'll want a better lat/long parsing routine
        // Format: "<latitude>,<longitude>" (must have comma, but only one comma)
        List<String> latlon = currentPosition.split(',');
        lat = latlon[0].trim();
        lon = latlon[1].trim();
        
        // SOQL query to get the nearest Contacts
        String queryString =
        'SELECT Id, Name, MailingStreet, MailingCity, MailingState, Phone, Location__longitude__s, Location__latitude__s ' +
        'FROM Contact ' +
        'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') < 20 ' +
        'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') ' +
        'LIMIT 10';
        System.Debug('>>>> the value of queryString is ' + queryString);
        // Run the query
        
        contacts = database.query(queryString);        
        return null;
    }
}

Visualforce Page:
<apex:page controller="FindNearbyController" docType="html-5.0" >

    <!-- JavaScript to get the user's current location, and pre-fill the currentPosition form field. -->
    <script type="text/javascript">
        // Get location, fill in search field
        function setUserLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(loc){
                    var latlon = loc.coords.latitude + "," + loc.coords.longitude;
                    var el = document.querySelector("input.currentPosition");
                    el.value = latlon;
                });
            }
        }
        // Only set the user location once the page is ready
        var readyStateCheckInterval = setInterval(function() {
            if (document.readyState === "interactive") {
                clearInterval(readyStateCheckInterval);
                setUserLocation();
            }
        }, 10);
    </script>
    
    <apex:pageBlock >
        <!-- Form field to send currentPosition in request. You can make it an <apex:inputHidden> field to hide it. -->
        <apex:pageBlockSection >
            <apex:form >
                <apex:outputLabel for="currentPosition">Find Nearby</apex:outputLabel> 
                <apex:input size="30" 
                     html-placeholder="Attempting to obtain your position..."
                     id="currentPosition" styleClass="currentPosition" 
                     value="{!currentPosition}" />
                <apex:commandButton action="{!findNearby}" value="Go!"/>
            </apex:form>
        </apex:pageBlockSection>
        
         <!-- Map of the results -->
        <apex:pageBlockSection rendered="{!resultsAvailable}" title="Locations">
            <apex:map width="500px" height="500px" center="53704">
            <!-- Add markers for contacts -->
                <apex:repeat value="{!contacts}" var="con">
                       <apex:mapMarker title="{!con.Name}"
                         position="{latitude:{!con.Location__latitude__s},longitude:{!con.Location__longitude__s}}">
                        <apex:mapInfoWindow >
                            <apex:outputPanel layout="block" style="font-weight: bold;">
                                <apex:outputText escape="false" value="{!con.Name}"/>
                            </apex:outputPanel>
                        </apex:mapInfoWindow>
                     </apex:mapMarker>
                </apex:repeat>
             </apex:map>
        </apex:pageBlockSection>        
    </apex:pageBlock>
</apex:page>

Let me know if you have any question on this.

Thank You,
Hitesh Patel
Email :- hiteshpatel.aspl@gmail.com
http://mrjavascript.blogspot.in/
 

All Answers

Abhishek BansalAbhishek Bansal
Hi Reshmi,

Please change your code as follows :
<apex:pageBlockSection rendered="{!resultsAvailable}" title="Locations">
            <apex:map width="600px" height="400px">
                <apex:repeat value="{!locations}" var="pos">
                    <apex:mapMarker position="{!pos}">
                        <!-- Add info window with contact details -->
                        <apex:mapInfoWindow >
                        <apex:outputPanel layout="block" style="font-weight: bold;">
                        <apex:repeat value="{!contacts}" var="con">
                            <apex:outputText>{!con.Name }</apex:outputText>
                        </apex:repeat>
                        </apex:outputPanel>
                      </apex:mapInfoWindow>
                    </apex:mapMarker>
                </apex:repeat>

            </apex:map>
        </apex:pageBlockSection>
Please make the changes as mentioned above in the code.
Let me know if you have any issue.

Thanks,
Abhishek
Reshmi SmijuReshmi Smiju
Hi Abhishek,

Thank you response. But this gives me an error . It seems like, we cant use Nested <apex:repeat> within an <apex:map>. Do u know , how to replce the expression with a Dynamic field Set.
Thanks
Reshmi
hitesh90hitesh90
Hello Reshmi,

Can you please post your full code here?
Reshmi SmijuReshmi Smiju
Hi Hitesh,

here is the code.

Thanks
Reshmi

Apex Class

public with sharing class 
FindNearbyController{
    public List<Map<String,Double>> locations { get; private set; }    
 public String currentPosition {          
get {             
if (String.isBlank(currentPosition)) {                 
currentPosition = '37.77493,-122.419416'; // San Francisco             }             
return currentPosition;         }         
set;      }          
public Boolean resultsAvailable {         
get {             if(locations == Null) {                 
return false;             }             
return true;         }     }          
public PageReference findNearby() {         
String lat, lon;         
// FRAGILE: You'll want a better lat/long parsing routine         
// Format: "<latitude>,<longitude>" (must have comma, but only one comma)         
List<String> latlon = currentPosition.split(',');         
lat = latlon[0].trim();         
lon = latlon[1].trim();         
// SOQL query to get the nearest Contacts            
// SOQL query to get the nearest Contacts
           String queryString =
           'SELECT Id, Name, MailingStreet, MailingCity, MailingState, Phone, Location__longitude__s, Location__latitude__s ' +
           'FROM Contact ' +
           'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') < 20 ' +
           'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') ' +
           'LIMIT 10';
        System.Debug('>>>> the value of queryString is ' + queryString);
        // Run the query
 
       List <Contact> contacts = database.query(queryString);
        if(contacts.size() > 0 ) {
            // Convert to locations that can be mapped
            locations = new List<Map<String,Double>>();
            for (Contact con : contacts) {
                locations.add( new Map<String,Double>{
                        'latitude' => con.Location__latitude__s,
                        'longitude' => con.Location__longitude__s
                    }
                );
            }
        }
        else {
            System.debug('No results. Query: ' + queryString);
        }
                
        return null;
    }
}

VF Code
<apex:page controller="FindNearbyController" docType="html-5.0" >

    <!-- JavaScript to get the user's current location, and pre-fill the currentPosition form field. -->
    <script type="text/javascript">
        // Get location, fill in search field
        function setUserLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(loc){
                    var latlon = loc.coords.latitude + "," + loc.coords.longitude;
                    var el = document.querySelector("input.currentPosition");
                    el.value = latlon;
                });
            }
        }
        // Only set the user location once the page is ready
        var readyStateCheckInterval = setInterval(function() {
            if (document.readyState === "interactive") {
                clearInterval(readyStateCheckInterval);
                setUserLocation();
            }
        }, 10);
    </script>
   <apex:pageBlock >
        <!-- Form field to send currentPosition in request. You can make it an <apex:inputHidden> field to hide it. -->
        <apex:pageBlockSection >
            <apex:form >
                <apex:outputLabel for="currentPosition">Find Nearby</apex:outputLabel>
                <apex:input size="30"
                     html-placeholder="Attempting to obtain your position..."
                     id="currentPosition" styleClass="currentPosition"
                     value="{!currentPosition}" />
                <apex:commandButton action="{!findNearby}" value="Go!"/>
            </apex:form>
        </apex:pageBlockSection>
        
        <!-- Map of the results -->
        <apex:pageBlockSection rendered="{!resultsAvailable}" title="Locations">
            <apex:map width="600px" height="400px">
            <!-- Add markers for contacts -->
                <apex:repeat value="{!locations}" var="pos">
                    <apex:mapMarker position="{!pos}"/>
                    <!-- Add info window with contact details -->
                    <apex:mapInfoWindow>
                    <apex:outputPanel layout="block" style="font-weight: bold;">
                    <apex:repeat value="{!contacts}" var="con">
                        <apex:outputText>{!con.Name }</apex:outputText>
                     </apex:repeat>
                     </apex:outputPanel>
                    </apex:mapInfoWindow>
                 </apex:repeat>
            </apex:map>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>
hitesh90hitesh90
Hello Reshmi,

There are some mistake in the existing code. please try to use below code.

Apex Class:
public with sharing class FindNearbyController{
    public List<Contact> contacts{ get; private set; }
    public String currentPosition { 
        get {
            if (String.isBlank(currentPosition)) {
                currentPosition = '37.77493,-122.419416'; // San Francisco
            }
            return currentPosition;
        }
        set; 
    }    
    public Boolean resultsAvailable {
        get {
            if(contacts == Null) {
                return false;
            }
            return true;
        }
    }
    
    public PageReference findNearby() {
        String lat, lon;
        
        // FRAGILE: You'll want a better lat/long parsing routine
        // Format: "<latitude>,<longitude>" (must have comma, but only one comma)
        List<String> latlon = currentPosition.split(',');
        lat = latlon[0].trim();
        lon = latlon[1].trim();
        
        // SOQL query to get the nearest Contacts
        String queryString =
        'SELECT Id, Name, MailingStreet, MailingCity, MailingState, Phone, Location__longitude__s, Location__latitude__s ' +
        'FROM Contact ' +
        'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') < 20 ' +
        'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') ' +
        'LIMIT 10';
        System.Debug('>>>> the value of queryString is ' + queryString);
        // Run the query
        
        contacts = database.query(queryString);        
        return null;
    }
}

Visualforce Page:
<apex:page controller="FindNearbyController" docType="html-5.0" >

    <!-- JavaScript to get the user's current location, and pre-fill the currentPosition form field. -->
    <script type="text/javascript">
        // Get location, fill in search field
        function setUserLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(loc){
                    var latlon = loc.coords.latitude + "," + loc.coords.longitude;
                    var el = document.querySelector("input.currentPosition");
                    el.value = latlon;
                });
            }
        }
        // Only set the user location once the page is ready
        var readyStateCheckInterval = setInterval(function() {
            if (document.readyState === "interactive") {
                clearInterval(readyStateCheckInterval);
                setUserLocation();
            }
        }, 10);
    </script>
    
    <apex:pageBlock >
        <!-- Form field to send currentPosition in request. You can make it an <apex:inputHidden> field to hide it. -->
        <apex:pageBlockSection >
            <apex:form >
                <apex:outputLabel for="currentPosition">Find Nearby</apex:outputLabel> 
                <apex:input size="30" 
                     html-placeholder="Attempting to obtain your position..."
                     id="currentPosition" styleClass="currentPosition" 
                     value="{!currentPosition}" />
                <apex:commandButton action="{!findNearby}" value="Go!"/>
            </apex:form>
        </apex:pageBlockSection>
        
         <!-- Map of the results -->
        <apex:pageBlockSection rendered="{!resultsAvailable}" title="Locations">
            <apex:map width="500px" height="500px" center="53704">
            <!-- Add markers for contacts -->
                <apex:repeat value="{!contacts}" var="con">
                       <apex:mapMarker title="{!con.Name}"
                         position="{latitude:{!con.Location__latitude__s},longitude:{!con.Location__longitude__s}}">
                        <apex:mapInfoWindow >
                            <apex:outputPanel layout="block" style="font-weight: bold;">
                                <apex:outputText escape="false" value="{!con.Name}"/>
                            </apex:outputPanel>
                        </apex:mapInfoWindow>
                     </apex:mapMarker>
                </apex:repeat>
             </apex:map>
        </apex:pageBlockSection>        
    </apex:pageBlock>
</apex:page>

Let me know if you have any question on this.

Thank You,
Hitesh Patel
Email :- hiteshpatel.aspl@gmail.com
http://mrjavascript.blogspot.in/
 
This was selected as the best answer