Skip to content

Instantly share code, notes, and snippets.

@sombochea
Last active June 12, 2024 02:44
Show Gist options
  • Save sombochea/0b96aa57f59d4cb89b29b5551c8f3591 to your computer and use it in GitHub Desktop.
Save sombochea/0b96aa57f59d4cb89b29b5551c8f3591 to your computer and use it in GitHub Desktop.
Find the distance between 2 locations given.
export const findDistanceOf2Locations = ({ target, source }: {
target: { lat: number, lon: number, fencingRadius: number },
source: { lat: number, lon: number }
}): {
distance: number,
isInside: boolean,
distancePretty: string // Format the distance in meters or kilometers (e.g. 100m or 1.5km)
} => {
const { lat: lat1, lon: lon1 } = source;
const { lat: lat2, lon: lon2, fencingRadius } = target;
const R = 6371000; // Radius of Earth in meters
const toRadians = (degrees) => degrees * (Math.PI / 180);
const phi1 = toRadians(lat1);
const phi2 = toRadians(lat2);
const deltaPhi = toRadians(lat2 - lat1);
const deltaLambda = toRadians(lon2 - lon1);
const a = Math.sin(deltaPhi / 2) ** 2 +
Math.cos(phi1) * Math.cos(phi2) *
Math.sin(deltaLambda / 2) ** 2;
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c; // Output distance in meters
const isInside = distance <= fencingRadius;
return {
distance,
isInside,
distancePretty: distance < 1000 ? `${distance.toFixed(0)}m` : `${(distance / 1000).toFixed(1)}km`
};
};
const ouput = findDistanceOf2Locations({
target: { lat: 11.11, lon: 104.11, fencingRadius: 100 },
source: { lat: 11.11, lon: 104.11 }
});
console.log(ouput);
import math
def haversine(lat1, lon1, lat2, lon2):
R = 6371000 # Radius of Earth in meters
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
delta_phi = math.radians(lat2 - lat1)
delta_lambda = math.radians(lon2 - lon1)
a = math.sin(delta_phi / 2.0) ** 2 + \
math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2.0) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c # Output distance in meters
return distance
# Example coordinates
lat1, lon1 = xxx, xxx # Target Location
lat2, lon2 = xxx, xxx # Source Location
distance = haversine(lat1, lon1, lat2, lon2)
print(f"Distance: {distance} meters")
# Check if within the fencing radius
fencing_radius = 100 # 100 meters
if distance <= fencing_radius:
print("Source is within the target's radius.")
else:
print("Source is outside the target's radius.")
@sombochea
Copy link
Author

Screenshot 2024-06-12 at 9 33 09 in the morning
Screenshot 2024-06-12 at 9 33 37 in the morning
Screenshot 2024-06-12 at 9 34 43 in the morning

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment