geolocation - using the haversine formula in javascript with variables -


hi have been struggling using have sine formula distance between users current location , objects in array, have found great answer question when try use variables instead of actual coordinates formula dosent work, 1 know going wrong

this question got me point, thank talkol answer

using haversine formula in javascript

this i've got far

  navigator.geolocation.getcurrentposition (function (posa) {   var lat = posa.coords.latitude.tofixed(6);   var lng = posa.coords.longitude.tofixed(6);  });      function getcurrent() {  var lat1 = lat;  var lon1 = lng;  var lat2 = 42.741;  var lon2 = -71.3161;   number.prototype.torad = function() {    return * math.pi / 180; }  var r = 6371; // km  //has problem .torad() method below. var x1 = lat2-lat1; var dlat = x1.torad();   var x2 = lon2-lon1; var dlon = x2.torad();   var = math.sin(dlat/2) * math.sin(dlat/2) +                  math.cos(lat1.torad()) * math.cos(lat2.torad()) *                  math.sin(dlon/2) * math.sin(dlon/2);   var c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a));  var d = r * c;   alert(d); var distance = d  $("#distance").val (distance); } 

i tried code working without errors. used own code. can see lat2&lon2 declared globally. 2 functions haversine() , deg2rad() declared outside load() ,with parameters,and return values.

<script type="text/javascript"> var lat2 = 42.741;  var lon2 = -71.3161;   function deg2rad(degrees){ radians = degrees * (math.pi/180); return radians; }  function haversine(lat1,lon1,lat2,lon2) {   deltalat = lat2 - lat1 ;   deltalon = lon2 - lon1 ;   earthradius =  6369087 ; // in meters 3959 in miles.   alpha    = deltalat/2;   beta     = deltalon/2;          = math.sin(deg2rad(alpha)) * math.sin(deg2rad(alpha)) + math.cos(deg2rad(lat1)) * math.cos(deg2rad(lat2)) * math.sin(deg2rad(beta)) * math.sin(deg2rad(beta)) ;   c        = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a));   distance =  earthradius * c;   return distance.tofixed(2); }  function load(){//called on page load if(navigator.geolocation)   {   navigator.geolocation.getcurrentposition(function(position)    {   var lat1 = position.coords.latitude.tofixed(6);   var lon1 = position.coords.longitude.tofixed(6);   var distance = haversine(lat1,lon1,lat2,lon2)+ " meters";   $("#distance").val (distance);      }); } } </script> 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -