Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How to create random longitude and latitudes?

Tags:

javascript

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; } 
like image 267
Evik James Avatar asked Jul 29 '11 20:07

Evik James


1 Answers

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 
like image 151
Sergey Metlov Avatar answered Oct 03 '22 04:10

Sergey Metlov