How to generate random Lat-lng values with known center and radius in javascript?
I want to create a heatmap layer at a radius of 100 meters and so I want to generate random lat-long values at that specific radius and so I want to replace it with
var taxiData = [
{location: new google.maps.LatLng(41.8819, -87.6278),weight: 2},
{location: new google.maps.LatLng(41.8820, -87.6279),weight: 1},
new google.maps.LatLng(41.8821, -87.6280),
{location: new google.maps.LatLng(41.8822, -87.6281),weight: 2},
{location: new google.maps.LatLng(41.8823, -87.6282),weight: 5},
{location: new google.maps.LatLng(41.8824, -87.6283),weight: 3},
];
please, help
+3
source to share
1 answer
This should allow you to do this.
What the code does:
First, we generate a fairly uniform random point inside the triangle and transform it to a point in a circle of radius. We then convert that point to offset coordinates and add them to the original.
An object containing two values latitude
and is returned longitude
.
var getRandomLocation = function (latitude, longitude, radiusInMeters) {
var getRandomCoordinates = function (radius, uniform) {
// Generate two random numbers
var a = Math.random(),
b = Math.random();
// Flip for more uniformity.
if (uniform) {
if (b < a) {
var c = b;
b = a;
a = c;
}
}
// It all triangles.
return [
b * radius * Math.cos(2 * Math.PI * a / b),
b * radius * Math.sin(2 * Math.PI * a / b)
];
};
var randomCoordinates = getRandomCoordinates(radiusInMeters, true);
// Earths radius in meters via WGS 84 model.
var earth = 6378137;
// Offsets in meters.
var northOffset = randomCoordinates[0],
eastOffset = randomCoordinates[1];
// Offset coordinates in radians.
var offsetLatitude = northOffset / earth,
offsetLongitude = eastOffset / (earth * Math.cos(Math.PI * (latitude / 180)));
// Offset position in decimal degrees.
return {
latitude: latitude + (offsetLatitude * (180 / Math.PI)),
longitude: longitude + (offsetLongitude * (180 / Math.PI))
}
};
+6
source to share