我正在尝试创建随机的经度和纬度。我需要创建介于-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;
}
发布于 2011-07-30 04:46:10
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
发布于 2011-07-30 04:43:03
Math.random()*360 - 180
这将得到-180到180的范围
如果你真的只想要3位小数
Math.round((Math.random()*360 - 180) * 1000)/1000
发布于 2011-07-30 04:45:40
function generateRandomLatLng()
{
var num = Math.random()*180;
var posorneg = Math.floor(Math.random());
if (posorneg == 0)
{
num = num * -1;
}
return num;
}
https://stackoverflow.com/questions/6878761
复制相似问题