gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:12:39 25 4
gpt4 key购买 nike

我正在尝试创建随机经度和纬度。我需要在之间创建数字-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;
}

最佳答案

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
}

在您的情况下:getRandomInRange(-180, 180, 3):

12.693
-164.602
-7.076
-37.286
52.347
-160.839

关于JavaScript - 如何创建随机经度和纬度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6878761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com