简体   繁体   中英

Javascript random number between coordinates

I would like to generate points between the following coordinates : 52.1462 ,5.8676 - 52.1536 ,5.8376 This is where my rectangle is drawn.

I got the following code to randomize points between this rectangle:

var x_min = rectangle.getBounds().getEast();
var x_max = rectangle.getBounds().getWest();
var y_min = rectangle.getBounds().getSouth();
var y_max = rectangle.getBounds().getNorth();


var lat = y_min + (Math.random() * (y_max - y_min));
var lng = x_min + (Math.random() * (x_max - x_min));


lngBrd.push([l , b ]); == My starting point. 
lngBrd.push([lng, lat]); == should be random inside the box
lngBrd.push([lng, lat]); == should be random inside the box

But it gives me coordinates outside to box, see the img.

在此处输入图片说明

Where goes this wrong?

Reply to the comment

If I log :

lngBrd.push([l , b ]); == My starting point. 
lngBrd.push([lng, lat]); == should be random inside the box
lngBrd.push([lng, lat]); == should be random inside the box

I get :

在此处输入图片说明

On every refresh. (This first one is correct, because thats my starting point)

I think x_min should be the rectangle.getBounds().getWest(); and x_max should be rectangle.getBounds().getEast(); assuming that we are in the 1st quadrant of a cartesian plane.

var x_min = rectangle.getBounds().getWest();
var x_max = rectangle.getBounds().getEast();
var y_min = rectangle.getBounds().getSouth();
var y_max = rectangle.getBounds().getNorth();

and since the coordinates are (52.1462 ,5.8676) (52.1536 ,5.8376) it might be useful to multiply the values first to 10000 then revert back after.

var x_min_int = x_min * 10000;
var x_max_int = x_max * 10000;
var y_min_int = y_min * 10000;
var y_max_int = y_max * 10000;

var lat_int = y_min_int + (Math.random() * (y_max_int - y_min_int));
var lng_int = x_min_int + (Math.random() * (x_max_int - x_min_int));

var lat = lat_int / 10000;
var lng = lng_int / 10000;

Since Math.random() works best on integers, proper randomization will work on the range of the rectangle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM