shoc-backend/Api.SeaHavenIndustries/Helper/ZipCodeDistance.cs
Adam Moussa 521bb0fba2 Add zip-to-zip distance calculation for vendor dispatch
- ZipCodeDistance helper with Haversine formula on 33K US zip code centroids
- Loaded as singleton from wwwroot/zipcodes.csv on startup
- Vendor Dropdown endpoint accepts siteZip, returns address and distanceMiles
- Vendors sorted by distance when siteZip provided
- Include locationZip in GetWorkorderById response
2026-04-17 11:56:06 -04:00

48 lines
1.9 KiB
C#

namespace Api.SeaHavenIndustries.Helper
{
public class ZipCodeDistance
{
private readonly Dictionary<string, (double lat, double lng)> _coords = new();
private bool _loaded;
public void Load(string csvPath)
{
if (_loaded) return;
foreach (var line in File.ReadLines(csvPath).Skip(1))
{
var parts = line.Split(',');
if (parts.Length >= 3
&& double.TryParse(parts[1].Trim(), out var lat)
&& double.TryParse(parts[2].Trim(), out var lng))
{
_coords[parts[0].Trim().PadLeft(5, '0')] = (lat, lng);
}
}
_loaded = true;
}
public double? GetDistanceMiles(string? zip1, string? zip2)
{
if (string.IsNullOrWhiteSpace(zip1) || string.IsNullOrWhiteSpace(zip2)) return null;
var z1 = zip1.Trim().PadLeft(5, '0');
var z2 = zip2.Trim().PadLeft(5, '0');
if (z1.Length > 5) z1 = z1.Substring(0, 5);
if (z2.Length > 5) z2 = z2.Substring(0, 5);
if (!_coords.TryGetValue(z1, out var c1) || !_coords.TryGetValue(z2, out var c2)) return null;
return Haversine(c1.lat, c1.lng, c2.lat, c2.lng);
}
private static double Haversine(double lat1, double lon1, double lat2, double lon2)
{
const double R = 3958.8;
var dLat = ToRad(lat2 - lat1);
var dLon = ToRad(lon2 - lon1);
var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Cos(ToRad(lat1)) * Math.Cos(ToRad(lat2)) *
Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
return R * 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
}
private static double ToRad(double deg) => deg * Math.PI / 180.0;
}
}