Call javascript function from your apex method

The basic need for me is to find distance between 2 accounts.
I have the lat and long of addresses in accounts stored in as custom fields in Account object.

In My VF page i have 2 lookups to choose the accounts. I also have a command button which would query the accounts and get the lat and long for these accounts. After which i need to call a javascript method

<apex:pageBlock title="Check Distance Between Vendors" mode="edit"  id="theBlock" >
    <apex:pageBlockButtons location="both">
        <apex:commandButton value="Find Distance" action="{!chkDistance}" rerender="theBlock"/>
    </apex:pageBlockButtons>
    <apex:pageBlockSection columns="2">
        <apex:inputfield value="{!Equipment.Ship_From__c}"></apex:inputfield>
        <apex:inputfield value="{!Equipment.ShipTo__c}"></apex:inputfield>
    </apex:pageBlockSection>
</apex:pageBlock>

My javascript function

function calculateDistances(){
    var origin1 = new google.maps.LatLng(55.930385, -3.118425); // hardcoded for now, these would come from the query of Account
    var destinationB = new google.maps.LatLng(50.087692, 14.421150);

    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
    {
        origins: [origin1],
        destinations: [destinationB],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, callback);   
}


function callback(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
        alert('Error was: ' + status);
    } else {
        alert(response);
    }
}

My query here is

  1. how do we call the javascript function after running the apex method to query on Accounts.
  2. How do we get the queried lat longs into the javascript

Thanks

Answer

Have you considered Javascript Remoting ?

Instead of using an actionbutton you could execute a javascript function launching a method in the controller. You’d receive a callback to javascript, where you can continue executing your required logic.

Documentation and an example can be found here: http://www.salesforce.com/us/developer/docs/pages/Content/pages_js_remoting.htm

Attribution
Source : Link , Question Author : Prady , Answer Author : Samuel De Rycke

Leave a Comment