Search code examples
javascriptnode.jsgeo

javascript (node.js) geo calc resulting in NaN


I am trying to do node+geo-stuff to retrieve all locations from given lat,long and radius for that calculation, i am trying below stuff, but it is resulting in NaN.

similar code is working fine in php,python, but could not figure it out what i am doing wrong here.

ref : http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL

PS 1: using nodejs for this calculation as it needs to calculate on server side. PS 2: even variable name looks like php variable, it is js.

$cat file.js

var log =console.log;
var cos=Math.cos;
var sin=Math.sin;

function rad2deg(x){ log("rad2deg:", x,180*x/Math.pi);return (180*x/Math.pi);}
function deg2rad(x){ log("deg2rad:",x,x*Math.pi/180);return (x*Math.pi/180);}

function getNearPoint($lat,$lng,$rad){

  console.log("Debug1",$lat,$lng);
  $R = 6371;  // earth's radius, km
  // first-cut bounding box (in degrees)
  $maxLat = $lat + rad2deg($rad/$R);
  $minLat = $lat - rad2deg($rad/$R);
  console.log("Debug2",$lat,$lng);
  // compensate for degrees lnggitude getting smaller with increasing latitude
  $maxlng = $lng + rad2deg($rad/$R/cos(deg2rad($lat)));
  $minlng = $lng - rad2deg($rad/$R/cos(deg2rad($lat)));

  console.log("Debug3",$lat,$lng);
  // convert origin of filter circle to radians
  $lat = deg2rad($lat);
  $lng = deg2rad($lng);

  console.log("Debug4",$lat,$lng);

//Build database query and do rest of the stuff
}

getNearPoint(19.1947659,72.8768400,50);

Here is the output.

$ node file.js

Debug1 19.1947659 72.87684
rad2deg: 0.007848061528802385 NaN
rad2deg: 0.007848061528802385 NaN
Debug2 19.1947659 72.87684
deg2rad: 19.1947659 NaN
rad2deg: NaN NaN
deg2rad: 19.1947659 NaN
rad2deg: NaN NaN
Debug3 19.1947659 72.87684
deg2rad: 19.1947659 NaN
deg2rad: 72.87684 NaN
Debug4 NaN NaN

Solution

  • There is no such constant as Math.pi. You probably want to use Math.PI (uppercase) instead. :)

    Math.pi is undefined and therefore will eventually just return NaN.