To improve the localization accuracy of wireless sensor networks, this study optimizes the centroid localization algorithm. In the ranging stage, received signal strength indicator (RSSI) values are preprocessed by both mean filtering and median filtering. In the localization stage, the centroid is weighted by the exponential power of the inverse distance. Furthermore, the idea of iteration is introduced to solve the problem that the nodes cannot be localized when the density of anchor nodes is low. The experimental results indicate that compared with the centroid localization algorithm and the distance-weighted centroid localization algorithm, the proposed modified algorithm can effectively improve the localization accuracy of wireless sensor networks.