## Using the Distance Formula with Angular

| |
[ 所属分类 前端（javascript） | 发布者 店小二03 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏
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.

• ### 技术变现模型：忽然有一天，企业的现金流断了怎么办？之企业三张表

1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责；
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性，不作出任何保证或承若；
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。