Call javascript function from your apex method

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


I'd upvote the Javascript Remoting answer if I was able :)

The other option (for completeness) is to:

  • Use the oncomplete attribute in the commandbutton (pass the name of the callback method)
  • Store the lat/long values in controller variables, and include them on the page with a style that hides them
  • Call your controller method - this should populate the variables, and re-render the part of the page that includes them with the new values
  • In the oncomplete method, grab the long/lat variables from the page and calculate the distance.

Not done the above, but as I understand it, that would work. Compared to Javascript Remoting however, it's nowhere near as neat.

Also, see this answer to a similar question: https://salesforce.stackexchange.com/a/574/167 I can't verify if it'll work, but presuming the math is right, you could save yourself a second callout.


Have you tried using AJAX instead

  1. Use this

    <script src="../../soap/ajax/23.0/connection.js" type="text/javascript"></script>
    
  2. On the Commandbutton onClick event, call the Javascript function by passing the AccountId's, something like

    onclick="calculateDistances('{!JSINHTMLENCODE(acctId1)}','{!JSINHTMLENCODE(acctId2)'});"
    
  3. In the javascript function, use sforce.connection.query() , now you should be getting the values for the further processing.