// Reference the points feature layer var patientsDA = FeatureSetByName($map,"PointsLayer") // Count the number of patients within each polygon var cntPatients = Intersects(patientsDA, $feature) // Group patients by their facility and count var stats = GroupBy(cntPatients, "facility_name", [ {name: "ClinicCount", expression: "facility_name", statistic: "COUNT"} ]) // Order the results in descending order by the total counts var topFacilities = Top(OrderBy(Filter(stats, "facility_name <> ''"),"ClinicCount desc"), 3) // Popup placeholder var result = '' // Write the results to the popup if(Count(topFacilities) == 0){ return "No Patients in this area" } var num = 0 // Format the results for display in popup for(var item in topClinics){ num++ var num_clinics = item.total var clinic_name = item["facility_name"] result += TextFormatting.NewLine + clinic+name } return result