The Addresses table uses Latitude and Longitude column names, not Lat and Lng. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
58 lines
2.2 KiB
Text
58 lines
2.2 KiB
Text
<cfscript>
|
|
function geocodeAddress(addressString) {
|
|
var result = { "success": false, "error": "" };
|
|
if (!len(trim(addressString))) { result.error = "Empty address"; return result; }
|
|
try {
|
|
var httpService = new http();
|
|
httpService.setMethod("GET");
|
|
httpService.setUrl("https://nominatim.openstreetmap.org/search?q=" & urlEncodedFormat(addressString) & "&format=json&limit=1");
|
|
httpService.addParam(type="header", name="User-Agent", value="Payfrit/1.0");
|
|
httpService.setTimeout(10);
|
|
var httpResult = httpService.send().getPrefix();
|
|
if (httpResult.statusCode CONTAINS "200") {
|
|
var data = deserializeJSON(httpResult.fileContent);
|
|
if (arrayLen(data) GT 0) {
|
|
result.success = true;
|
|
result.lat = data[1].lat;
|
|
result.lng = data[1].lon;
|
|
return result;
|
|
}
|
|
result.error = "No results found";
|
|
} else {
|
|
result.error = "HTTP " & httpResult.statusCode;
|
|
}
|
|
} catch (any e) { result.error = e.message; }
|
|
return result;
|
|
}
|
|
|
|
function buildAddressString(line1, line2, city, zipCode) {
|
|
var parts = [];
|
|
if (len(trim(line1))) arrayAppend(parts, trim(line1));
|
|
if (len(trim(line2))) arrayAppend(parts, trim(line2));
|
|
if (len(trim(city))) arrayAppend(parts, trim(city));
|
|
if (len(trim(zipCode))) arrayAppend(parts, trim(zipCode));
|
|
return arrayToList(parts, ", ");
|
|
}
|
|
|
|
function geocodeAddressById(addressId) {
|
|
var qAddr = queryExecute("
|
|
SELECT Line1, Line2, City, ZIPCode
|
|
FROM Addresses WHERE ID = :id
|
|
", { id: addressId }, { datasource: "payfrit" });
|
|
|
|
if (qAddr.recordCount == 0 || !len(trim(qAddr.Line1))) return;
|
|
|
|
var fullAddress = buildAddressString(qAddr.Line1, qAddr.Line2, qAddr.City, qAddr.ZIPCode);
|
|
var geo = geocodeAddress(fullAddress);
|
|
|
|
if (geo.success) {
|
|
queryExecute("
|
|
UPDATE Addresses SET Latitude = :lat, Longitude = :lng WHERE ID = :id
|
|
", {
|
|
lat: { value: geo.lat, cfsqltype: "cf_sql_decimal" },
|
|
lng: { value: geo.lng, cfsqltype: "cf_sql_decimal" },
|
|
id: addressId
|
|
}, { datasource: "payfrit" });
|
|
}
|
|
}
|
|
</cfscript>
|