JavaScript - How to create random longitude and latitudes?

后端 未结 6 1318
礼貌的吻别
礼貌的吻别 2020-12-24 12:47

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 y

相关标签:
6条回答
  • 2020-12-24 13:01
    Math.random()*360 - 180
    

    that will get you a range of -180 to 180

    And if you really only want 3 decimal places

    Math.round((Math.random()*360 - 180) * 1000)/1000
    
    0 讨论(0)
  • 2020-12-24 13:01

    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.

    0 讨论(0)
  • 2020-12-24 13:04

    This should work

    Math.random() * 360 - 180
    
    0 讨论(0)
  • 2020-12-24 13:06
    function generateRandomLatLng()
    {
        var num = Math.random()*180;
        var posorneg = Math.floor(Math.random());
        if (posorneg == 0)
        {
            num = num * -1;
        }
        return num;
    }
    
    0 讨论(0)
  • 2020-12-24 13:09
    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):

    12.693
    -164.602
    -7.076
    -37.286
    52.347
    -160.839
    
    0 讨论(0)
  • 2020-12-24 13:21

    You can try 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
    0 讨论(0)
提交回复
热议问题