我想创造随机的经度和纬度.我需要在-180.000和+180.000之间创建数字.所以,我可能得到101.325或-3.546或-179.561.
你能告诉我一个快速的公式吗?
感谢大家的帮助.我结合了几个例子来满足我的需求.是的,我可以缩短代码,但这确实有助于了解正在发生的事情.
// 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;
}
Run Code Online (Sandbox Code Playgroud)
Ser*_*lov 64
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
}
Run Code Online (Sandbox Code Playgroud)
在你的情况下getRandomInRange(-180, 180, 3)::
12.693
-164.602
-7.076
-37.286
52.347
-160.839
Run Code Online (Sandbox Code Playgroud)
Math.random()*360 - 180
Run Code Online (Sandbox Code Playgroud)
这将使你获得-180到180的范围
如果你真的只想要3位小数
Math.round((Math.random()*360 - 180) * 1000)/1000
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18386 次 |
| 最近记录: |