How to determine if the location is set under specific radius

How to determine if the location is set under specific radius
Photo by Thomas Kinto / Unsplash

Here is an example of a TypeScript class that can be used to check if a given latitude and longitude point is within a specified radius:

class LatLonRadiusChecker { private radius: number; constructor(radius: number) { this.radius = radius; } public isInRadius(lat: number, lon: number, centerLat: number, centerLon: number): boolean { // convert lat/lon to radians lat = lat * (Math.PI / 180); lon = lon * (Math.PI / 180); centerLat = centerLat * (Math.PI / 180); centerLon = centerLon * (Math.PI / 180); // calculate deltas const deltaLat = lat - centerLat; const deltaLon = lon - centerLon; // calculate the haversine formula const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.cos(centerLat) * Math.cos(lat) * Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); // calculate the distance in kilometers const distance = 6371 * c; return distance <= this.radius; } < code>

To use this class, you would first need to create an instance of it, passing in the radius in kilometers that you want to use for the check:

const checker = new LatLonRadiusChecker(50); // radius of 50 km>

You can then use the isInRadius() method to check if a given latitude and longitude point is within the specified radius:

const isInRadius = checker.isInRadius(40.7127, -74.0059, 39.9042, 116.4074); // New York City and Beijing // isInRadius is false

Note that the isInRadius() method expects the latitude and longitude values to be in decimal degrees. If you have the values in another format, you will need to convert them before using the method.

Great! Next, complete checkout for full access to n10.
Welcome back! You've successfully signed in.
You've successfully subscribed to n10.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.