3 Replies Latest reply on Sep 4, 2013 8:59 AM by Dino Gregorich

    Convert Javascript math function to Ruby

    Dino Gregorich

      I have a JavaScript function that calculates direction based on current lat/long and last lat/long:

      function calcDirection(l_lat, c_lat, l_lng, c_lng)


      var result;

      fRadians = Math.atan2((l_lng - c_lng ),(l_lat - c_lat));

      result = fRadians * 180 / Math.PI;

      if(result < 0) {

      result += 360; // degrees are 0-360


      return result;



      I need to write it in Ruby running Rho 2.2 on Windows Mobile 6.5.  Or can I call it from Ruby?...if so, how I do I get the result from JavaScript to Ruby?

      Thank you.

        • Re: Convert Javascript math function to Ruby
          Kutir Mobility

          Ruby also has a Math module with the atan2 function, so the conversion is very straightforward; the following should work:


          def calcDirection(l_lat, c_lat, l_lng, c_lng)
              fRadians = Math::atan2((l_lng - c_lng), (l_lat - c_lat))
              result = fRadians * 180 / Math::PI
              if (result < 0)
                    result = result + 360


          (edited answer to fix double colon in Math::atan2 for the benefit of anyone else who comes across this in the future)

            • Re: Convert Javascript math function to Ruby
              Dino Gregorich


              Thanks for the code.  I ran it in the Rho Simulator, and it worked like a charm.  However, more often than not, the simulator behaves differently than the actual Device especially for us WM6.5 folks, and in this case, the code failed.


              This is the error on the device:

                    App error: Numerical argument is out of domain - "atan2"

                    apps/app/Location/location_controller.rb:151:in `atan2'

                   apps/app/Location/location_controller.rb:151:in `calcDirection'

                   apps/app/Location/location_controller.rb:66:in `update_location'

                   lib/rho/rhocontroller.rb:104:in `serve'

                   lib/rho/rhoapplication.rb:248:in `serve'

                   lib/rho/rho.rb:883:in `serve'


              Any ideas why this kind of error happens on the device but not the Simulator?  Thanks. -Dino

                • Re: Convert Javascript math function to Ruby
                  Dino Gregorich


                  You were correct after all.  I had copied the sample code you provided and tested on the Rho Simulator and it worked.  But when I tried to run it on the Device, it failed.  After careful review, I noticed double colon between Math and PI...so I tried Math::atan2 (not Math.atan2).  Then ran it on the device...it worked!


                  Thanks for the assist!

                  1 of 1 people found this helpful