search functionality, kinda hacky

This commit is contained in:
Will Freeman
2024-10-04 15:09:41 -05:00
parent 64da95d76a
commit 0f432e724f
4 changed files with 150 additions and 5 deletions
+48
View File
@@ -54,3 +54,51 @@ export const getALPRs = async (boundingBox: BoundingBox) => {
const response = await apiService.get(`/alpr?${queryParams.toString()}`);
return response.data;
}
export const geocodeQuery = async (query: string, currentLocation: any) => {
const encodedQuery = encodeURIComponent(query);
const results = (await apiService.get(`/geocode?query=${encodedQuery}`)).data;
function findNearestResult(results: any, currentLocation: any) {
console.log(currentLocation, results);
let nearestResult = results[0];
let nearestDistance = Number.MAX_VALUE;
for (const result of results) {
const distance = Math.sqrt(
Math.pow(result.lat - currentLocation.lat, 2) +
Math.pow(result.lon - currentLocation.lng, 2)
);
if (distance < nearestDistance) {
nearestResult = result;
nearestDistance = distance;
}
}
return nearestResult;
}
if (!results.length) return null;
const cityStatePattern = /(.+),\s*(\w{2})/;
const postalCodePattern = /\d{5}/;
if (cityStatePattern.test(query)) {
console.debug("cityStatePattern");
const cityStateResults = results.filter((result: any) =>
["city", "town", "village", "hamlet", "suburb", "quarter", "neighbourhood", "borough"].includes(result.addresstype)
);
if (cityStateResults.length) {
return findNearestResult(cityStateResults, currentLocation);
}
}
if (postalCodePattern.test(query)) {
console.debug("postalCodePattern");
const postalCodeResults = results.filter((result: any) => result.addresstype === "postcode");
if (postalCodeResults.length) {
return findNearestResult(postalCodeResults, currentLocation);
}
}
console.debug("defaultPattern");
return findNearestResult(results, currentLocation);
}