The iPhone uses assisted GPS to improve the accuracy of the location system using GPS and cell towers. Wi-Fi networks are used to help determine the device's location; this is called a hybrid positioning system (XPS).
Prior to iOS 4 iOS tapped into the Skyhook Wireless database of Wi-Fi hotspots and their locations. Apple disclosed in April 2010 that they had switched over to their own proprietary database.
If Location Services is on, your device will periodically send the geo-tagged locations of nearby Wi-Fi hotspots and cell towers in an anonymous and encrypted form to Apple, to augment the crowd-sourced database of Wi-Fi hotspot and cell tower locations. In addition, if you are traveling (for example, in a car) and Location Services is on, a GPS-enabled iOS device will also periodically send GPS locations and travel speed information in an anonymous and encrypted form to Apple, to be used for building up a crowd-sourced road traffic database. The crowd-sourced location data gathered by Apple does not personally identify you.
For your security concerns, read this Apple press release.