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 you tell me a quick formula for that?
Thanks to everyone for your help. I have combined a couple of examples to suit my needs. Yes, I could shorten the code, but this really helps to see what's going on.
// LONGITUDE -180 to + 180 function generateRandomLong() { var num = (Math.random()*180).toFixed(3); var posorneg = Math.floor(Math.random()); if (posorneg == 0) { num = num * -1; } return num; } // LATITUDE -90 to +90 function generateRandomLat() { var num = (Math.random()*90).toFixed(3); 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With