JavaScript - 如何创建随机经度和纬度? [英] JavaScript - How to create random longitude and latitudes?

查看:163
本文介绍了JavaScript - 如何创建随机经度和纬度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建随机经度和纬度。我需要在
-180.000和+180.000之间创建数字。所以,我可能得到101.325或-3.546或-179.561。

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.

你能告诉我一个快速公式吗?

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;
}


推荐答案

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 - 如何创建随机经度和纬度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆