IPhone application development: GPS Positioning System

Source: Internet
Author: User

IPhone application development: GPS Positioning System

Nowadays, mobile devices with GPS functions are becoming more and more common. GPS positioning systems can be used to precisely locate your current location, but since GPS receivers need to be aligned with the sky, therefore, indoor environments are useless.
Another effective way to find your location is to use the mobile phone base station. When the mobile phone is turned on, it will keep in touch with the surrounding base station. If you know the identity of these base stations, you can use a variety of databases (including the identity of the base station and their exact geographic location) to calculate the physical location of the mobile phone. The base station does not need satellites. Unlike GPS, it works in the same indoor environment. But it is not as accurate as GPS, and its precision depends on the density of the base station. It has the highest accuracy in base station-intensive areas.
Tip: No GPS receiver is configured for the first-generation iPhone. The base station method cannot be applied to the iPod Touch because it is not a mobile phone.
The third method is to rely on Wi-Fi. When using this method, the device connects to the Wi-Fi network and determines the location by checking the data of the service provider. It neither depends on satellites nor on base stations, therefore, this method is effective for areas that can be connected to Wi-Fi networks, but its accuracy is also the worst among the three methods.
Locating framework Kernel
On the iPhone, Apple provides the positioning framework kernel to help you determine your physical location. The beauty of this framework is that it uses all the three methods mentioned above, which method is used is transparent to developers. Developers only need to specify the required precision, and the positioning kernel will determine the positioning result in the best way.
Are you surprised ?! The rest of this article will show you how this is done.
Obtain coordinates
Use Xcode to create a new view-based application project named LBS. in the new project, double-click the LBSViewController. xib file and edit it in the interface design tool. Fill the View window with the following components, as shown in 1.
L Label
L TextField


Figure 1 Location view instance: Fill the window with Label and TextFiled
Right-click the Framework Group in Xcode, select "add" * "existing Framework", and select "Framework/CoreLocation. to LBSViewController. add the following code in bold text to the H file:
# Import <UIKit/UIKit. h>
# Import <CoreLocation/CoreLocation. h>
@ Interface LBSViewController: UIViewController
<CLLocationManagerDelegate> {
IBOutlet UITextField * latitudeTextField;
IBOutlet UITextField * longitudeTextField;
IBOutlet UITextField * accuracyTextField;
CLLocationManager * lm;
}
@ Property (retain, nonatomic) UITextField * latitudeTextField;
@ Property (retain, nonatomic) uitextfield * longitudetextfield;
@ Property (retain, nonatomic) uitextfield * accuracytextfield;
@ End if you want to use the cllocationmanager class, you need to implement the cllocationmanagerdelegate protocol in your view controller class. You also need to create three outlets to connect the three textfiled views in the View window.
Return to the interface editor, click and drag the document owner project to the three textfield views, and select latitudetextfield, longitudetextfield, and accuracytextfield respectively.
Query the bold Section in the following code in the lbsviewcontroller. M file:
# Import "lbsviewcontroller. H"
@ Implementation lbsviewcontroller
@ Synthesize latitudetextfield, longitudetextfield, accuracytextfield;
-(Void) viewdidload {
Lm = [[cllocationmanager alloc] init];
If ([lm locationservicesenabled]) {
Lm. Delegate = self;
Lm. desiredaccuracy = kcllocationaccuracybest;
Lm. distanceFilter = 1000.0f;
[Lm startUpdatingLocation];
}
}
-(Void) locationManager: (CLLocationManager *) manager
DidUpdateToLocation: (CLLocation *) newLocation
FromLocation: (CLLocation *) oldLocation {
NSString * lat = [[NSString alloc] initWithFormat: @ "% g ",
NewLocation. coordinate. latitude];
LatitudeTextField. text = lat;

NSString * lng = [[NSString alloc] initWithFormat: @ "% g ",
NewLocation. coordinate. longpolling];
LongitudeTextField. text = lng;

NSString * acc = [[NSString alloc] initWithFormat: @ "% g ",
NewLocation. horizontalAccuracy];
AccuracyTextField. text = acc;

[Acc release];
[Lat release];
[Lng release];
}
-(Void) locationManager: (CLLocationManager *) manager
DidFailWithError: (NSError *) error {
NSString * msg = [NSString alloc]
InitWithString: @ "Error obtaining location"];
UIAlertView * alert = [[UIAlertView alloc]
InitWithTitle: @ "Error"
Message: msg
Delegate: nil
CancelButtonTitle: @ "Done"
OtherButtonTitles: nil];
[Alert show];
[Msg release];
[Alert release];
}
-(Void) dealloc {
[Lm release];
[LatitudeTextField release];
[LongitudeTextField release];
[AccuracyTextField release];
[Super dealloc];
} The previous Code creates an instance of the CLLocationManager class. Before using an object, you should check whether the user has enabled the device location service. If yes, you can use the desiredAccuracy attribute to specify the expected precision and use the following constant to specify the expected precision:
L kCLLocationAccuracyBest
L kCLLocationAccuracyNearestTenMeters
L kCLLocationAccuracyHundredMeters
L kCLLocationAccuracyKilometer
L kCLLocationAccuracyThreeKilometers
The distanceFilter attribute allows you to specify the distance and location information that the device must move to update. The unit of this attribute is meter. If you want to get all the moving notifications, you can use the kCLDistanceFilterNone constant and start the Location Manager using the startUpdatingLocation method.
To obtain location information, you must handle the following two events:
L locationManager: didUpdateToLocation: fromLocation:
L locationManager: didFailWithError:
When a new location value is obtained, the device triggers the locationManager: didUpdateToLocation: fromLocation: event. If the location manager cannot determine the location information, it triggers the locationManager: didFailWithError: event.
When the device can determine the location, you may want to display the longitude and latitude values and precision. In this case, you can use the CLLocation object. Its horizontalAccuracy attribute can specify the precision range, in meters.
Run the Command-r Command to test the program on the iPhone simulator. Figure 2 shows the latitude and longitude values of the simulator and the accuracy.
Figure 2 positioning test: These fixed values are always displayed when you test the sample program on the iPhone Simulator

 

Show Map
It will be even more interesting to locate the location coordinates on the Map. Fortunately, the iPhone 3.0 SDK includes the Map Kit API, which allows you to display Google Map in your program, the following is an example.
Or use the project created earlier to add a button in the visual window in the LBSViewController. xib file, as shown in figure 3.


Figure 3 View Map button: After adding a button
Right-click the framework Group in Xcode and add a new framework MapKit. framework. Add the bold part in the following code in the LBSViewController. h file:
# Import <UIKit/UIKit. h>
# Import <CoreLocation/CoreLocation. h>
# Import <MapKit/MapKit. h>
@ Interface LBSViewController: UIViewController
<CLLocationManagerDelegate> {
IBOutlet UITextField * accuracyTextField;
IBOutlet UITextField * latitudeTextField;
IBOutlet UITextField * longitudeTextField;
CLLocationManager * lm;

MKMapView * mapView;
}
@ Property (retain, nonatomic) UITextField * accuracyTextField;
@ Property (retain, nonatomic) UITextField * latitudeTextField;
@ Property (retain, nonatomic) UITextField * longitudeTextField;

-(IBAction) btnViewMap: (id) sender;

@ End return to the interface editor, drag the button to the owner project of the file, and select btnViewMap :.
In the LBSViewController. m file, add the bold Section in the following code:
-(IBAction) btnViewMap: (id) sender {
[Self. view addSubview: mapView];
}
-(Void) viewDidLoad {
Lm = [[CLLocationManager alloc] init];
Lm. delegate = self;
Lm. desiredAccuracy = kCLLocationAccuracyBest;
Lm. distanceFilter = 1000.0f;
[Lm startUpdatingLocation];

MapView = [[MKMapView alloc] initWithFrame: self. view. bounds];
MapView. mapType = MKMapTypeHybrid;
}
-(Void) locationManager: (CLLocationManager *) manager
DidUpdateToLocation: (CLLocation *) newLocation
FromLocation: (CLLocation *) oldLocation {
NSString * lat = [[NSString alloc] initWithFormat: @ "% g ",
NewLocation. coordinate. latitude];
LatitudeTextField. text = lat;

NSString * lng = [[NSString alloc] initWithFormat: @ "% g ",
NewLocation. coordinate. longpolling];
LongitudeTextField. text = lng;

NSString * acc = [[NSString alloc] initWithFormat: @ "% g ",
NewLocation. horizontalAccuracy];
AccuracyTextField. text = acc;

[Acc release];
[Lat release];
[Lng release];

MKCoordinateSpan span;
Span. latitudeDelta =. 005;
Span. longitudeDelta =. 005;

MKCoordinateRegion region;
Region. center = newLocation. coordinate;
Region. span = span;

[MapView setRegion: region animated: TRUE];
}
-(Void) dealloc {
[MapView release];
[Lm release];
[LatitudeTextField release];
[LongitudeTextField release];
[AccuracyTextField release];
[Super dealloc];
}

Code explanation:
L when a view is loaded, create an instance of the MKMapView class and set the displayed map type.
L when you click the View Map Button, add a mapView object to the current View.
L when the location information is updated, use the setRegion: Method of the mapView object to enlarge the map.
In the iPhone simulator, press Command-r to test the program. Click View Map to display a Map containing the location returned by the location manager. 4.


Figure 4 map location: display the map location by locating the kernel framework
Because the simulator always displays the same location. If you have an iPhone, you can actually feel it. When you move the location, you will see that the map is automatically updated. Set the distanceFilter attribute to a smaller value to enhance the tracking experience.
As you can see, the positioning kernel framework of the iPhone SDK allows you to easily implement location-based devices. In addition, MapKit (included in the iPhone SDK) the location information can be displayed on the map. If you haven't created a location-based application, I think you should try it after reading this article. What are you waiting?

 

 

 

The above content is reproduced from: http://www.3gtarena.com/News_View.asp? Newsid= 1270

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.