created service to calculate distance between two coordinates

This commit is contained in:
grata
2023-04-03 15:39:55 +02:00
parent be9bbe76cf
commit 96b93d4d42
2 changed files with 28 additions and 20 deletions

View File

@@ -1,5 +1,6 @@
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {CalculateDistanceService} from "../service/calculateDistance.service";
@Component({
selector: 'app-detail',
@@ -10,7 +11,7 @@ export class DetailComponent implements OnInit {
private location: string | undefined;
private id: number | undefined;
constructor(private route: ActivatedRoute) {
constructor(private route: ActivatedRoute , private calculateDistanceService: CalculateDistanceService) {
}
ngOnInit(): void {
@@ -65,7 +66,7 @@ export class DetailComponent implements OnInit {
let lon2 = this.test.cordinates.split(",")[1];
let intervalID = setInterval(() => {
if (this.showNav) {
this.distance = this.getDistanceBetweenCoordinates(lat1, lon1, +lat2, +lon2);
this.distance = this.calculateDistanceService.getDistanceBetweenCoordinates(lat1, lon1, +lat2, +lon2);
console.log(this.distance);
if (this.distance == 0) {
this.showNav = false;
@@ -82,23 +83,5 @@ export class DetailComponent implements OnInit {
}, 1000);
}
getDistanceBetweenCoordinates(lat1: number, lon1: number, lat2: number, lon2: number) {
const earthRadius = 6371; // Radius of the earth in km
const dLat = this.deg2rad(lat2 - lat1); // deg2rad below
const dLon = this.deg2rad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2)
;
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// Distance in km
return earthRadius * c;
}
deg2rad(deg: number) {
return deg * (Math.PI / 180)
}
///
}

View File

@@ -0,0 +1,25 @@
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CalculateDistanceService{
getDistanceBetweenCoordinates(lat1: number, lon1: number, lat2: number, lon2: number) {
const earthRadius = 6371; // Radius of the earth in km
const dLat = this.deg2rad(lat2 - lat1); // deg2rad below
const dLon = this.deg2rad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2)
;
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// Distance in km
return earthRadius * c;
}
deg2rad(deg: number) {
return deg * (Math.PI / 180)
}
}