I modified the code slightly and checked into a few things.
// Define search parameters
var searchDistanceKm = 50; // Search distance in kilometers
// Access weather stations from the Living Atlas
// Source: Environment Canada dataset
var weatherStationsFS = FeatureSetByPortalItem(
"38406bada3104e258fc8b42a2a96581a", // Item ID for the dataset
0, // Layer index
["Temperature_C"], // Attributes to include
true // Spatial filtering flag
);
// Find weather stations within the search distance
var nearbyWeatherStations = Intersects(
weatherStationsFS,
Buffer($feature, searchDistanceKm, "kilometers")
);
// Initialize variables to track the closest station
var minDistance = Infinity;
var closestStationTemperature = null;
// Iterate through nearby stations to find the closest one
for (var station in nearbyWeatherStations) {
var distanceToStation = Round(Distance(station, $feature, "kilometers"), 2);
if (distanceToStation < minDistance) {
closestStationTemperature = station["Temperature_C"];
minDistance = distanceToStation;
}
}
// Output the result based on whether a close station was found
if (closestStationTemperature != null) {
return "Closest Weather Station Temperature is " + closestStationTemperature + "°C and is located approximately " + Round(minDistance, 0) + " km away.";
} else {
return "No closest weather station was found within the search distance.";
}