代码区项目交易流程

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.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

点击收藏

LAST Integration Key to Experience: Common Elements (Part 2) 关于高效、高质和高产 NEXT