|
| 1 | +import { DataResult } from '../../types' |
| 2 | + |
| 3 | +export const createFullText = (data: DataResult) => { |
| 4 | + const keys = ['code', 'village', 'district', 'regency', 'province'] |
| 5 | + const combinations: string[] = [] |
| 6 | + |
| 7 | + keys.forEach((a, x) => { |
| 8 | + keys.forEach((b, y) => { |
| 9 | + if (x !== y) { |
| 10 | + combinations.push(`${data[a]} ${data[b]}`) |
| 11 | + } |
| 12 | + }) |
| 13 | + }) |
| 14 | + |
| 15 | + return combinations.join(' ') |
| 16 | +} |
| 17 | + |
| 18 | +export const haversineDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => { |
| 19 | + const R = 6371 // earth radius in km |
| 20 | + const dLat = ((lat2 - lat1) * Math.PI) / 180 |
| 21 | + const dLon = ((lon2 - lon1) * Math.PI) / 180 |
| 22 | + const a = |
| 23 | + Math.sin(dLat / 2) * Math.sin(dLat / 2) + |
| 24 | + Math.cos((lat1 * Math.PI) / 180) * |
| 25 | + Math.cos((lat2 * Math.PI) / 180) * |
| 26 | + Math.sin(dLon / 2) * |
| 27 | + Math.sin(dLon / 2) |
| 28 | + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) |
| 29 | + |
| 30 | + return R * c // distance in km |
| 31 | +} |
| 32 | + |
| 33 | +export const nearestDetection = ( |
| 34 | + data: DataResult[], |
| 35 | + lat: number, |
| 36 | + lon: number |
| 37 | +): DataResult | null => { |
| 38 | + let nearest: DataResult | null = null |
| 39 | + let smallestDistance = Infinity |
| 40 | + |
| 41 | + data.forEach((item) => { |
| 42 | + const distance = haversineDistance(lat, lon, item.latitude, item.longitude) |
| 43 | + |
| 44 | + if (distance < smallestDistance) { |
| 45 | + nearest = item |
| 46 | + smallestDistance = distance |
| 47 | + nearest.distance = distance |
| 48 | + } |
| 49 | + }) |
| 50 | + |
| 51 | + return nearest |
| 52 | +} |
0 commit comments