JavaScript - 如何创建随机的经度和纬度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6878761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - How to create random longitude and latitudes?
提问by Evik James
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.
我正在尝试创建随机的经度和纬度。我需要在 -180.000 和 +180.000 之间创建数字。所以,我可能会得到 101.325 或 -3.546 或 -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;
}
回答by Sergey Metlov
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)
:
在你的情况下getRandomInRange(-180, 180, 3)
::
12.693
-164.602
-7.076
-37.286
52.347
-160.839
回答by Joseph Marikle
Math.random()*360 - 180
that will get you a range of -180 to 180
这将为您提供 -180 到 180 的范围
And if you really only want 3 decimal places
如果你真的只想要 3 个小数位
Math.round((Math.random()*360 - 180) * 1000)/1000
回答by slandau
function generateRandomLatLng()
{
var num = Math.random()*180;
var posorneg = Math.floor(Math.random());
if (posorneg == 0)
{
num = num * -1;
}
return num;
}
回答by John Kalberer
This should work
这应该工作
Math.random() * 360 - 180
回答by Jason Kaczmarsky
Here is a function I made that does this:
这是我做的一个函数:
function Rand(x, y){
//Returns a random number between 0 and X if Y is undefined
//Returns a random number between X and Y if Y is defined
return x+(Math.random()*(y-x)) || Math.random()*x;
}
This works with integers as well as floats.
这适用于整数和浮点数。
回答by Hemil Patel
You can try http://www.geomidpoint.com/random/
你可以试试http://www.geomidpoint.com/random/
Features:
特征:
- Random Location in Circular region - centred at the starting point
- Random Location in Rectangular region - north, south, west and east limits
- Retrieve Locations in different formates like csv and json
- 圆形区域中的随机位置 - 以起点为中心
- 矩形区域中的随机位置 - 北、南、西和东界限
- 检索不同格式的位置,如 csv 和 json