Skip to content

Instantly share code, notes, and snippets.

@yoadsn
Last active October 10, 2017 06:25
Show Gist options
  • Select an option

  • Save yoadsn/586a4cd223499c75eea15b4a66728cd9 to your computer and use it in GitHub Desktop.

Select an option

Save yoadsn/586a4cd223499c75eea15b4a66728cd9 to your computer and use it in GitHub Desktop.
Calculate a random geo point on a circle radius
const R = 6371e3; // Earth radius in meters (approximated)
const fromRadians = (rad) => rad / (Math.PI / 180);
const toRadians = (deg) => deg * (Math.PI / 180);
const getPointOnRadius = (center, radius, angle) => {
const phi1 = toRadians(center.lat);
const lambda1 = toRadians(center.lng);
const theta = toRadians(angle);
const d = radius;
const phi2 = Math.asin( Math.sin(phi1)*Math.cos(d/R) +
Math.cos(phi1)*Math.sin(d/R)*Math.cos(theta) );
const lambda2 = lambda1 + Math.atan2(Math.sin(theta)*Math.sin(d/R)*Math.cos(phi1),
Math.cos(d/R)-Math.sin(phi1)*Math.sin(phi2));
return {
lat: fromRadians(phi2),
lng: (fromRadians(lambda2)+540)%360-180
};
}
const center = {
lat: 0,
lng: 0
};
const angle = (Math.random() - 0.5) * 360;
const distance = 1000;
const point = getPointOnRadius(center, distance, angle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment