The accuracy of node localization plays a crucial role in the performance and reliability of wireless sensor networks (WSNs), which are widely utilized in fields like security systems and environmental monitoring. The integrity of these networks is often threatened by the presence of malicious nodes that can disrupt the localization process, leading to erroneous positioning and degraded network functionality. To address this challenge, we propose the security-aware localization using bat-optimized malicious anchor prediction (BO-MAP) algorithm. This approach utilizes a refined bat optimization algorithm to improve both the precision of localization and the security of WSNs. By integrating advanced optimization with density-based clustering and probabilistic analysis, BO-MAP effectively identifies and isolates malicious nodes. Our comprehensive simulation results reveal that BO-MAP significantly surpasses six current state-of-the-art methods—namely, the Secure Localization Algorithm, Enhanced DV-Hop, Particle Swarm Optimization-Based Localization, Range-Free Localization, the Robust Localization Algorithm, and the Sequential Probability Ratio Test—across various performance metrics, including the true positive rate, false positive rate, localization accuracy, energy efficiency, and computational efficiency. Notably, BO-MAP achieves an impressive true positive rate of 95% and a false positive rate of 5%, with an area under the receiver operating characteristic curve of 0.98. Additionally, BO-MAP exhibits consistent reliability across different levels of attack severity and network conditions, highlighting its suitability for deployment in practical WSN environments.