Using the Distance Formula with Angular

getRadarStationClosest(observationStations: {}, lat: string, long: string): string {
  const radarStations = <any> observationStations;
  let closestStation = '';
  let firstTime = true;
  let minDistance = 0;

  const x1: number = parseFloat(long);
  const y1: number = parseFloat(lat);

  radarStations.forEach((element) => {
    // when calculating distance use the distance formula
    // sqrt of (x2-x1)^2 + (y2-y1)^2
    // long = x
    // lat = y
    const x2: number = parseFloat(element['geometry']['coordinates'][0]);
    const y2: number = parseFloat(element['geometry']['coordinates'][1]);
    const xSquared: number = (x2 - x1) * (x2 - x1);
    const ySquared: number = (y2 - y1) * (y2 - y1);
    const distance = Math.sqrt(xSquared + ySquared);

    if (firstTime) {
      firstTime = false;
      minDistance = distance;
      closestStation = element['id'];
    } else {
      if (distance < minDistance) {
        minDistance = distance;
        closestStation = element['id'];
      }
    }
  });

  return closestStation;
}

When I was working on my Angular weather app I recently had to use the distance formula from Algebra and wanted to share it here.

The reason I was using it was to find the nearest radar station given coordinates (latitude and longitude). I was using an endpoint that gave me a set of radar stations for an area, and I needed to identify the closest one.

After some testing, I found out that the NOAA APIs that I was using actually provided more accurate readings with a different endpoint that didn’t require me to do this math.

I thought using the distance formula was still cool, and just wanted to post it here for future reference. Also checkout the following video on how to use the distance formula.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s