JavaScript - 如何创建随机经度和纬度?

Evi*_*mes 24 javascript

我想创造随机的经度和纬度.我需要在-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)

  • OP确实要求一个“快速公式”,所以这可能没问题,但请注意,它容易被忽视对两极附近点的偏见。有关问题的解释和替代方法,请参阅 http://mathworld.wolfram.com/SpherePointPicking.html,不可否认,这些方法不会那么“快”。 (2认同)

Jos*_*kle 5

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)

  • `.fix(3)`是将数字四舍五入到小数点后3位的更好方法 (2认同)