Add location filtering based on ZIP + Country

This commit is contained in:
2025-09-01 13:31:06 -07:00
parent fa35b084bc
commit 72fb4f2536
4 changed files with 134 additions and 4 deletions
@@ -0,0 +1,95 @@
using BoredCareers.Entities;
using MySql.Data.MySqlClient;
using System.Data;
using System.Data.Common;
using System.Text;
namespace BoredCareers.Services.DatabaseService {
public partial class DatabaseService {
public async Task<Location?> GetLocation(string PostalCode, string CountryCode) {
using (MySqlConnection connection = GetConnection()) {
await connection.OpenAsync();
string command = @"
SELECT PostalCode, CountryCode, Latitude, Longitude, City
FROM PostalCodes
WHERE PostalCode = @PostalCode
AND CountryCode = @CountryCode;
";
MySqlCommand cmd = new MySqlCommand(command, connection);
cmd.Parameters.AddWithValue("@PostalCode", PostalCode);
cmd.Parameters.AddWithValue("@CountryCode", CountryCode);
using (DbDataReader reader = await cmd.ExecuteReaderAsync()) {
while (await reader.ReadAsync()) {
string _city = reader.GetString("City");
string _postalCode = reader.GetString("PostalCode");
string _countryCode = reader.GetString("CountryCode");
float _latitude = reader.GetFloat("Latitude");
float _longitude = reader.GetFloat("Longitude");
return new Location() {
City = _city,
PostalCode = _postalCode,
CountryCode = _countryCode,
Latitude = _latitude,
Longitude = _longitude
};
}
}
}
return null;
}
public async Task<Location[]> GetNearbyLocations(float Latitude, float Longitude, string CountryCode, float MaxDistanceKm) {
List<Location> closePostalCodes = new List<Location>();
using (MySqlConnection connection = GetConnection()) {
await connection.OpenAsync();
string command = @"
SELECT PostalCode, CountryCode, Latitude, Longitude, City, (
6371 * acos(
cos(radians(@Latitude)) *
cos(radians(Latitude)) *
cos(radians(Longitude) - radians(@Longitude)) +
sin(radians(@Latitude)) *
sin(radians(Latitude))
)
) AS distance_km
FROM PostalCodes
WHERE countrycode = @CountryCode
HAVING distance_km <= @MaxDistanceKm
ORDER BY distance_km;
";
MySqlCommand cmd = new MySqlCommand(command, connection);
cmd.Parameters.AddWithValue("@Latitude", Latitude);
cmd.Parameters.AddWithValue("@Longitude", Longitude);
cmd.Parameters.AddWithValue("@CountryCode", CountryCode);
cmd.Parameters.AddWithValue("@MaxDistanceKm", MaxDistanceKm);
using (DbDataReader reader = await cmd.ExecuteReaderAsync()) {
while (await reader.ReadAsync()) {
string _city = reader.GetString("City");
string _postalCode = reader.GetString("PostalCode");
string _countryCode = reader.GetString("CountryCode");
float _latitude = reader.GetFloat("Latitude");
float _longitude = reader.GetFloat("Longitude");
float _distanceKm = reader.GetFloat("distance_km");
closePostalCodes.Add(new Location() {
City = _city,
PostalCode = _postalCode,
CountryCode = _countryCode,
Latitude = _latitude,
Longitude = _longitude,
DistanceKM = _distanceKm
});
}
}
}
return closePostalCodes.ToArray();
}
}
}