Location acquisition position and position coding-anti-coding
Our application can get the map location of the device by adding the classes contained in the core location framework.
Add the Corelocation.framework frame and import the #import<corelocation/corelocation.h>.
Using the Map service consumes more device power. Therefore, when you get to the location of the device, you should stop positioning to conserve electricity.
We use a demo to show the content and effect
Copy Code code as follows:
//
HMTRootViewController.h
My-gps-map
//
Created by HMT on 14-4-12.
Copyright (c) 2014 Hu Mingtao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface Hmtrootviewcontroller:uiviewcontroller <CLLocationManagerDelegate>
@end
//
Hmtrootviewcontroller.m
My-gps-map
//
Created by HMT on 14-4-12.
Copyright (c) 2014 Hu Mingtao. All rights reserved.
//
#import "HMTRootViewController.h"
#import <AddressBook/AddressBook.h>
@interface Hmtrootviewcontroller () {
Cllocationmanager * _locationmanage;
}
@property (nonatomic,retain) Cllocationmanager * locationmanage;
@end
@implementation Hmtrootviewcontroller
-(void) dealloc{
Release_safely (_locationmanage);
[Super Dealloc];
}
-(ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *) Nibbundleornil
{
self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil];
if (self) {
Custom initialization
}
return self;
}
-(void) viewdidload
{
[Super Viewdidload];
Do no additional setup after loading the view.
[Self creategpsmap];
Self.view.backgroundColor = [Uicolor Redcolor];
}
-(void) creategpsmap{
Initialize Location service
Self.locationmanage = [[Cllocationmanager alloc]init];
Require Cllocationmanager object to return all information
_locationmanage.distancefilter = Kcldistancefilternone;
Set positioning precision
_locationmanage.desiredaccuracy = Kcllocationaccuracybest;
Set up agents
_locationmanage.delegate = self;
Start positioning
[_locationmanage startupdatinglocation];
[_locationmanage release];
}
-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) locations{
Cllocation * newlocation = [locations Lastobject];
Stop real-time positioning
[_locationmanage stopupdatinglocation];
Obtain latitude and longitude degree
Cllocationcoordinate2d coord2d = newlocation.coordinate;
Double latitude = coord2d.latitude;
Double longitude = coord2d.longitude;
NSLog (@ "latitude =%f longitude =%f", latitude,longitude);
Get the Accuracy
Cllocationaccuracy horizontal = newlocation.horizontalaccuracy;
Cllocationaccuracy vertical = newlocation.verticalaccuracy;
NSLog (@ "Horizontal side =%f Vertical side =%f", horizontal,vertical);
Get high
Cllocationdistance altitude = newlocation.altitude;
NSLog (@ "%f", altitude);
Get This Moment
NSDate *timestamp = [newlocation timestamp];
Instantiate a NSDateFormatter object
nsdateformatter* DateFormat = [[NSDateFormatter alloc] init];
Set time format
[DateFormat setdateformat:@ "Yyyy-mm-dd HH:mm:ss a"];
[DateFormat setamsymbol:@ "AM"]; Show Chinese, change to "morning"
[DateFormat setpmsymbol:@ "PM"];
Find the time string for the day, and the time string changes as you change the time format
NSString *datestring = [DateFormat stringfromdate:timestamp];
NSLog (@ "At this moment time =%@", datestring);
-----------------------------------------Position-coded--------------------------------------------
Clgeocoder * Geocoder = [[Clgeocoder alloc]init];
[Geocoder reversegeocodelocation:newlocation completionhandler:^ (Nsarray *placemarks, NSError *error) {
For (Clplacemark * place in Placemarks) {
NSLog (@ "name =%@", place.name); Location name
NSLog (@ "thoroughfare =%@", place.thoroughfare); Street
NSLog (@ "Subadministrativearea =%@", Place.subadministrativearea); Zi Jie dao
NSLog (@ "locality =%@", place.locality); City
NSLog (@ "sublocality =%@", place.sublocality); Area
NSLog (@ "country =%@", place.country); Countries
Nsarray *allkeys = Place.addressDictionary.allKeys;
For (NSString *key in AllKeys)
{
NSLog (@ "key =%@, value =%@", key, Place.addressdictionary[key]);
}
#pragma mark-Use a system-defined string to query directly, remember to import the AddressBook framework
NSLog (@ "Kabpersonaddresscitykey =%@", (NSString *) kabpersonaddresscitykey);
NSLog (@ "city =%@", place.addressdictionary[(NSString *) kabpersonaddresscitykey));
NSString *city = place.locality;
if (city = = nil)
{
City = place.addressdictionary[(NSString *) Kabpersonaddressstatekey];
}
}
}];
}
-(void) didreceivememorywarning
{
[Super didreceivememorywarning];
Dispose of any of the can is recreated.
}
@end
Program Run Result: (Take 39.3,116.4 as an example)
Copy Code code as follows:
To determine the address entered
if (Self.locationTextField.text = = Nil | | [Self.locationTextField.text length] = = 0) {
Return
}
Clgeocoder *geocoder = [[Clgeocoder alloc] init];
/*-----------------------------------------Position Code--------------------------------------------* *
[Geocoder geocodeaddressstring:_locationtextfield.text completionhandler:^ (Nsarray *placemarks, NSError *error) {
For (Clplacemark *placemark in Placemarks) {
cllocationcoordinate2d coordinate = placemark.location.coordinate;
NSString *strcoordinate = [NSString stringwithformat:@ "latitude =%3.5f\n longitude =%3.5f", Coordinate.latitude, Coordinate.longitude];
NSLog (@ "%@", strcoordinate);
Nsdictionary *addressdictionary = placemark.addressdictionary;
NSString *address = [addressdictionary objectforkey: (NSString *) Kabpersonaddressstreetkey];
NSString *state = [addressdictionary objectforkey: (NSString *) Kabpersonaddressstatekey];
NSString *city = [addressdictionary objectforkey: (NSString *) Kabpersonaddresscitykey];
NSLog (@ "street =%@\n province =%@\n City =%@", address,state,city);
}
}];
The use of maps and the marking of maps
Use the Corelocation framework to get the location of the current device, which describes the use of the map.
First, import <MapKit.framework> framework:
Copy Code code as follows:
#import <MapKit/MapKit.h>
Main code example
Copy Code code as follows:
Main.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
Reference Map Protocol
@interface hmtmainviewcontroller:uiviewcontroller<mkmapviewdelegate>
@end
Main.m
//
Hmtmainviewcontroller.m
Map
//
Created by HMT on 14-6-21.
Copyright (c) 2014 Humingtao. All rights reserved.
//
#import "HMTMainViewController.h"
#import "HMTAnnotation.h"
@interface Hmtmainviewcontroller ()
@property (nonatomic, strong) Mkmapview *mapview;
@end
@implementation Hmtmainviewcontroller
-(ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *) Nibbundleornil
{
self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil];
if (self) {
Custom initialization
}
return self;
}
-(void) viewdidload
{
[Super Viewdidload];
Self.view.backgroundColor = [Uicolor Redcolor];
Do no additional setup after loading the view.
Self.navigationItem.title = @ "Map callout";
Self.mapview = [[Mkmapview alloc] Initwithframe:cgrectmake (0, 0, 320, 568)];
Whether to display the user's current position
Self.mapView.showsUserLocation = YES;
Set up agents
Self.mapView.delegate = self;
Map Display Type
/**
* Mkmaptypestandard = 0,//Standard map
* Mkmaptypesatellite,//satellite map
* Mkmaptypehybrid//Mixed map
*/
Self.mapView.mapType = Mkmaptypestandard;
Warp latitude
Cllocationcoordinate2d coord2d = {39.910650,116.47030};
Display range, the larger the number, the larger the range
Mkcoordinatespan span = {0.1,0.1};
Show Area
Mkcoordinateregion region = {Coord2d,span};
Set up a display area for a map
[Self.mapview setregion:region Animated:yes];
Whether to allow scaling
self.mapView.zoomEnabled = NO;
Whether to allow scrolling
self.mapView.scrollEnabled = NO;
Initialize a custom annotation (you can set multiple)
Hmtannotation *annotation = [[Hmtannotation alloc] initwithcglocation:coord2d];
Set Title
Annotation.title = @ "Custom callout location";
Set sub Headings
Annotation.subtitle = @ "sub-title";
Add annotations to the map (this step will perform the following proxy method Viewforannotation)
[Self.mapview addannotation:annotation];
[Self.view Addsubview:_mapview];
}
Return to the label gaze (pin view)
-(Mkannotationview *) Mapview: (Mkmapview *) Mapview viewforannotation: (id<mkannotation>) annotation{
/**
* Is it a bit like a custom UITableViewCell
*/
static NSString *identifier = @ "annotation";
Mkpinannotationview (pin View, inherited from Mkannotation)
Mkpinannotationview *annotationview = (Mkpinannotationview *) [Mapview dequeuereusableannotationviewwithidentifier: Identifier];
if (Annotationview = = nil) {
Annotationview = [[Mkpinannotationview alloc] initwithannotation:annotation reuseidentifier:identifier];
}
Determine if the callout view is customized
if ([Annotation iskindofclass:[hmtannotation class]]) {
Set PIN Circle Color
Annotationview.pincolor = Mkpinannotationcolorgreen;
Click on the red circle of the first needle to see if the above set title view
Annotationview.canshowcallout = YES;
To customize the anchor point picture, consider using Mkannotationview; Mkpinannotationview can only be shown as a PIN!!!!
Annotationview.image = [UIImage imagenamed:@ "Customimage"];
Add a title view to the right view (and the left view, you can view the API in detail)
UIButton *button = [UIButton buttonwithtype:uibuttontypedetaildisclosure];
[Button addtarget:self action: @selector (didclickannotationviewrightbuttonaction:) forControlEvents: UIControlEventTouchUpInside];
Annotationview.rightcalloutaccessoryview = button;
Whether to display annotations as animations (from the sky)
Annotationview.animatesdrop = YES;
annotationview.annotation = annotation;
Returns a custom callout view
return annotationview;
}else{
Callout view for current device location, returns nil, and the current position creates a default callout view
return nil;
}
}
-(void) Didclickannotationviewrightbuttonaction: (UIButton *) button{
NSLog (@ "%d%s", __line__,__function__);
}
Update current Location call
-(void) Mapview: (Mkmapview *) Mapview didupdateuserlocation: (mkuserlocation *) userlocation{
NSLog (@ "%d%s", __line__,__function__);
}
Select the winning eye chart
-(void) Mapview: (Mkmapview *) Mapview Didselectannotationview: (Mkannotationview *) view{
NSLog (@ "%d%s", __line__,__function__);
}
The actual area of the map changed the call
-(void) Mapview: (Mkmapview *) Mapview regiondidchangeanimated: (BOOL) animated{
NSLog (@ "%d%s", __line__,__function__);
}
-(void) didreceivememorywarning
{
[Super didreceivememorywarning];
Dispose of any of the can is recreated.
}
@end
Custom Mkannotationview
Copy Code code as follows:
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
Introduce the Mkannotation protocol, remember not to forget!!!!!!!!!
@interface hmtannotation:nsobject<mkannotation>
@property (nonatomic,readonly) cllocationcoordinate2d coordinate; Coordinate
@property (nonatomic,copy) NSString *title; Location name
@property (nonatomic,copy) NSString *subtitle; Location Sub Information (optional)
-(ID) initwithcglocation: (cllocationcoordinate2d) coordinate;
@end
#import "HMTAnnotation.h"
@implementation Hmtannotation
-(ID) initwithcglocation: (cllocationcoordinate2d) coordinate{
if (self = [super init]) {
_coordinate = coordinate;
}
return self;
}
@end
Effect Chart: