I am trying to create random longitude and latitudes. I need to create numbers between -180.000 and +180.000. So, I might get 101.325 or -3.546 or -179.561.
Can y
Math.random()*360 - 180
that will get you a range of -180 to 180
And if you really only want 3 decimal places
Math.round((Math.random()*360 - 180) * 1000)/1000
Here is a function I made that does this:
function Rand(x, y){
//Returns a random number between 0 and X if Y is undefined
//Returns a random number between X and Y if Y is defined
return x+(Math.random()*(y-x)) || Math.random()*x;
}
This works with integers as well as floats.
This should work
Math.random() * 360 - 180
function generateRandomLatLng()
{
var num = Math.random()*180;
var posorneg = Math.floor(Math.random());
if (posorneg == 0)
{
num = num * -1;
}
return num;
}
function getRandomInRange(from, to, fixed) {
return (Math.random() * (to - from) + from).toFixed(fixed) * 1;
// .toFixed() returns string, so ' * 1' is a trick to convert to number
}
In your case: getRandomInRange(-180, 180, 3)
:
12.693
-164.602
-7.076
-37.286
52.347
-160.839
You can try http://www.geomidpoint.com/random/
Features: