[SalesForce] passing variable from JS to Apex

I have Vf page to get the current user loged in location, But i am not able to pass the CurrentPosition value from VF page to apex.

setUserLocation is method in JS , it gets the current user location interms of latitude and longitude. I need to pass this value to apex variable(CurrentPosition )

can anyone help me?

VF Page

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




    </apex:pageBlock>

</apex:page>

Controller class:

public with sharing class FindNearbyController {

    public List<Map<String,Double>> locations { get; private set; }
     public Account cont {get;set;}
    public String selectedCountry1{get;set;}
    public String agentId{get;set;}
    public String distance{get;set;}
    public String currentPosition {get;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)

        system.debug('currentPosition'+currentPosition)// here it is showing null
        List<String> latlon = currentPosition.split(',');

        lat = latlon[0].trim();

        return null;
    }
}

Best Answer

Here is a simple example on how to pass a variable from JS to Apex. See the inline comments for details. You can use the same approach to resolve your problem.

Visulaforce Page:

<apex:page showHeader="true" sidebar="true" controller="SampleController">
    <script type="text/javascript">
           window.onload = function(){
               //this is calling the apex:actionFunction below with the same name when the page loads
               setUserLocation('11,13');
               console.log('setUserLocation called');
           }
   </script>

    <apex:form >
        <!-- this action function can be called from javascript -->
        <apex:actionFunction name="setUserLocation" action="{!setUserLocationInApex}" rerender="">
            <apex:param name="userLocation" value="" />
        </apex:actionFunction>
    </apex:form>

</apex:page>

Controller:

public with sharing class SampleController{
    public String currentPosition {get;set;}

    //this method is called with apex:actionFunction in VF page
    public PageReference setUserLocationInApex() {
        //the name of the parameter must be the same as it set in apex:param tag
        this.currentPosition = Apexpages.currentPage().getParameters().get('userLocation');

        System.debug('currentPosition >>>>> ' + currentPosition);

        return null;
    }
}

You can also take a look at the official documentation for additional information.