This article briefly introduces how to use GPS. Using GPS is roughly divided into the following two steps.
Add CoreLocation. framework.
Generate the CLLocationManager measurement position.
The test code is as follows:
// LocationViewCtrl. h
# Import <UIKit/UIKit. h>
# Import <CoreLocation/CoreLocation. h>
@ Interface LocationViewCtrl: UIViewController <CLLocationManagerDelegate> {
CLLocationManager * man;
}
@ Property (nonatomic, retain) CLLocationManager * man;
@ End
LocationViewCtrl. m
# Import "LocationViewCtrl. h"
# Import <CoreLocation/CoreLocation. h>
@ Implementation LocationViewCtrl
@ Synthesize man;
-(Void) viewDidLoad {
[Super viewDidLoad];
Man = [[CLLocationManager alloc] init];
// If you can use the local service
If ([man locationServicesEnabled]) {
// The instance that receives the event
Man. delegate = self;
// Minimum distance between events (unspecified by default)
Man. distanceFilter = kCLDistanceFilterNone;
// Precision (Best by default)
Man. desiredAccuracy = kCLLocationAccuracyBest;
// Start Measurement
[Man startUpdatingLocation];
}
}
// If the function below the GPS measurement result is called
-(Void) locationManager :( CLLocationManager *) manager
DidUpdateToLocation :( CLLocation *) newLocation
FromLocation :( CLLocation *) oldLocation {
// Obtain the longitude and latitude
CLLocationCoordinate2D coordinate = newLocation. coordinate;
CLLocationDegrees latitude = coordinate. latitude;
CLLocationDegrees longpolling = coordinate. longpolling;
// Obtain the precision
CLLocationAccuracy horizontal = newLocation. horizontalAccuracy;
CLLocationAccuracy vertical = newLocation. verticalAccuracy;
// Get height
CLLocationDistance altitude = newLocation. altitude;
// Get time
NSDate * timestamp = [newLocation timestamp];
// Output format in the following format: <latitude>, <longpolling> +/-<accuracy> m @ <date-time>
NSLog ([newLocation description]);
// Distance from the last measurement location
If (oldLocation! = Nil ){
CLLocationDistance d = [newLocation getDistanceFrom: oldLocation];
NSLog ([NSString stringWithFormat: @ "% f", d]);
}
}
// If GPS measurement fails, the following function is called
-(Void) locationManager :( CLLocationManager *) manager
DidFailWithError :( NSError *) error {
NSLog ([error localizedDescription]);
}
...
There are the following types of measurement accuracy: the higher the accuracy, the more power consumption.
KCLLocationAccuracyNearestTenMeters 10 m
KCLLocationAccuracyHundredMeters 100 m
KCLLocationAccuracyKilometer 1 km
KCLLocationAccuracyThreeKilometers 3km
Because longitude and latitude cannot be set on the simulator, you can only test your GPS program on the actual device.
Author: Yi Feiyang