In this study, a total of 180 Pinus eldarica bark samples were collected from different regions of Hamedan megacity, Iran, in 2023, and contents of Cd, Cr, Cu, Mn, Ni, Pb, and Zn in the samples were determined using ICP-OES. The results illustrated that the average contents of all the analyzed elements were greater than those in the background contents, which presumably demonstrated anthropogenic sources of these potentially toxic elements (PTEs). The greatest concentrations of the analyzed PTEs for different functional areas were observed in specimens collected from commercial or industrial areas, indicating the impact of human entries. The I-geo values were in the range of "unpolluted to moderately polluted" to "moderately to heavily polluted", PI showed "moderate to very high pollution", and PLI reflected high to very high pollution levels for the whole study area. Additionally, the cumulative mean value of ecological risk (RI) was found to be 152, demonstrating moderate ecological risk across the study area. The results of positive matrix factorization (PMF) showed that the PTE contamination in the air of Hamedan could mainly have an anthropogenic origin (82.7%) and that the traffic emissions as the primary pollution source (33.6%) make the highest contribution to the PTE pollution and ecological risks in the study area. In residential areas, demolition and construction activities could be considered the main sources of PTEs, while in commercial and industrial areas traffic emissions and industrial emissions, could be regarded as the main sources of such pollution, respectively. In conclusion, this study provides a useful approach to identifying the sources and contributions of the toxic elements in different functional areas and can inform future endeavors that aim at managing and controlling metal element pollution.