Geo Check In on the Browser

Thu Jun 08 2023

Browser provides location API to get the location of the user. So it is possible to do geo check-in in a web application.

Here are some fundamental codes to do so:

1. Get the location of the user

/**
 * Gets the current location of the user
 */
export const getCurrentLocation = async (): Promise<GeolocationPosition> => {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject, {
      enableHighAccuracy: true,
      timeout: 15000,
      maximumAge: 0
    });
  });
}

// Now you have cordinates of the user
async function main() {
  const { coords: { latitude, longitude } } = await getCurrentLocation();
  console.log(latitude, longitude);
}

2. Calculate Distance

/**
 * Calculate the distance between two points on the earth
 * @param lat1 Latitude 1
 * @param lon1 Longitude 1
 * @param lat2 Latitude 2
 * @param lon2 Longitude 2
 */
export const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
  const R = 6371e3; // Radius of the earth in meters
  const phi1 = lat1 * Math.PI / 180; // Latitude 1 in radians
  const phi2 = lat2 * Math.PI / 180; // Latitude 2 in radians
  const deltaPhi = (lat2 - lat1) * Math.PI / 180; // Difference in latitude in radians
  const deltaLambda = (lon2 - lon1) * Math.PI / 180; // Difference in longitude in radians

  const a = Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +
    Math.cos(phi1) * Math.cos(phi2) *
    Math.sin(deltaLambda / 2) * Math.sin(deltaLambda / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  // Distance in meters
  return R * c;
};