Map and location
tags (space delimited): UI Supplement
Map and location
In the era of mobile internet, we can rely on the mobile phone map navigation area unfamiliar places, also can use the group purchase app to search the nearest restaurant, find a hotel, find a bank, find a movie theater ....
-Lbs:location Based Service
-Solomo:social Local Mobile (Solomon)
The above features are all used in the map and positioning function, in iOS development, in order to join these 2 major functions, must be based on 2 frameworks for development
-Map Kit: for maps
-Core location: for geolocation
Basic use of Core location
- Starting with iOS 6, Apple has done a great job of protecting the privacy of its users, and the following must be authorized by user approval
- Get the user's location
- Access users ' contacts, calendars, cameras, albums, and more
When you want to access the user's privacy information, the system will automatically pop up a dialog box to let the user authorize
Once the user chooses "Don't allow", it means your app won't be able to use the targeting feature
Developers can set nslocationusagedescription in info.plist to explain the purpose of positioning
Simple to use
Cllocationmanager
- (void) Viewdidload {[SuperViewdidload];//1. Get the user's authorization status (IOS7 will request authorization directly if used to locate)Clauthorizationstatus status = [Cllocationmanager authorizationstatus];if(Status = = kclauthorizationstatusnotdetermined) {if([ Self. MgrRespondstoselector:@selector(requestalwaysauthorization)]) { [ Self. MgrRequestalwaysauthorization]; } }//2. Start positioning (when the method is called, the system keeps updating the user's location)[ Self. MgrStartupdatinglocation];}#pragma mark-Lazy loading-(Cllocationmanager *) mgr{if(_mgr = =Nil) { Self. Mgr= [[Cllocationmanager alloc] init];//Set agent, in the proxy method can get the user's location Self. Mgr. Delegate= Self;//Set positioning accuracy (higher accuracy, more power consumption) Self. Mgr. Desiredaccuracy= Kcllocationaccuracybestfornavigation;//Set to reposition when the user moves Self. Mgr. Distancefilter=10.0; }return_mgr;}
Cllocation
Cllocation the geographic information used to represent a location, such as latitude and longitude, altitude, etc.
@property(readonly, nonatomic) CLLocationCoordinate2D coordinate;
@property(readonly, nonatomic) CLLocationDistance altitude;
@property(readonly, nonatomic) CLLocationDirection course;
- Course, course (value range is 0.0°~ 359.9°,0.0° represents true north direction)
@property(readonly, nonatomic) CLLocationSpeed speed;
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location
- Calculate the distance between 2 positions
Clgeocoder
- Use Clgeocoder to complete geocoding and anti-geocoding
- Geocoding: Obtain specific location information (such as latitude and longitude, full name of address, etc.) based on a given place name
- Anti-geocoding: Obtain specific location information based on a given latitude and longitude
Geo-coding methods
- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;
Anti-geocoding methods
- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;
When Geo-geocoding is complete, it calls theCLGeocodeCompletionHandler
typedef void (^CLGeocodeCompletionHandler)(NSArray *placemarks, NSError *error);
- This block passes 2 parameters
- Error: There is a value when the encoding is wrong (for example, no specific information is encoded)
- Placemarks: It contains Clplacemark objects.
Clplacemark
Clplacemark literally means a landmark, encapsulating detailed address location information
@property (nonatomic, readonly) CLLocation *location;
@property (nonatomic, readonly) CLRegion *region;
@property (nonatomic, readonly) NSDictionary *addressDictionary;
- Detailed address information
@property (nonatomic, readonly) NSString *name;
@property (nonatomic, readonly) NSString *locality;
- Geo-coding
- (ibaction) GeoCode {NSString*address = @"Tiananmen Square";//geo-coding[ Self. GeocoderGeocodeaddressstring:address completionhandler:^ (Nsarray*placemarks,Nserror*error) {if(Error | | placemarks. Count==0)return; for(Clplacemark *pm in Placemarks) {//Get the full name of the address NSLog(@"%@"Pm. Name);//Get latitude and longitudecllocationcoordinate2d coordinate = PM. location. Coordinate;NSLog(@"Latitude:%.2f", coordinate. Latitude);NSLog(@"Longitude:%.2f", coordinate. Longitude);//Get the city NSLog(@"City:%@"Pm. Administrativearea);NSLog(@"City:%@"Pm. Locality); } }];}
- Anti-geo-coding
Pull two text boxes and an anti-geocoding button in the storyboard, and click the button to reverse-GeoCode the code.
- (ibaction) Reversegeocode {//1. Get the latitude and longitude of user input NSString*latitude = Self. Latitudefield. Text;NSString*longitude = Self. Longitudefield. Text;if(Latitude. Length==0|| Longitude. Length==0) {NSLog(@"Longitude or latitude cannot be empty");return; }//2. Anti-geocodingCllocation *location = [[Cllocation alloc] Initwithlatitude:latitude. DoublevalueLongitude:longitude. Doublevalue]; [ Self. GeocoderReversegeocodelocation:location completionhandler:^ (Nsarray*placemarks,Nserror*error) {if(Error | | placemarks. Count==0)return; for(Clplacemark *pm in Placemarks) {//Get the full name of the address NSLog(@"%@"Pm. Name);//Get latitude and longitudecllocationcoordinate2d coordinate = PM. location. Coordinate;NSLog(@"Latitude:%.2f", coordinate. Latitude);NSLog(@"Longitude:%.2f", coordinate. Longitude);//Get the city NSLog(@"City:%@"Pm. Administrativearea);NSLog(@"City:%@"Pm. Locality); } }];}
Use of the Mapkitmapkit framework
- The Mapkit framework uses the same steps as the corelocation framework, importing the framework first and then importing the primary header file
- The prefix for all data types in the Mapkit framework is MK
- Mapkit has a more important UI control: Mkmapview, specifically for map display
Trace displays the user's location
- Set the Usertrackingmode property of Mkmapview to track the current location of the user
- Mkusertrackingmodenone: Do not track the user's location
- Mkusertrackingmodefollow: Track and display the user's current location on the map
- Mkusertrackingmodefollowwithheading: Tracks and displays the user's current location on the map, which rotates with the user's forward direction
The blue Glow origin is the user's current position, the blue Glow Origin professional term is called "pin".
Map type
- You can set the map type by setting the Mapviewtype of Mkmapview
- Mkmaptypestandard: General map (left)
- Mkmaptypesatellite: Satellite cloud Image (Central)
- Mkmaptypehybrid: General map over satellite cloud image (right)
Mkmapview's agent
Mkmapview can set up a proxy object to listen to the map's related behavior
The common proxy methods are
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation;
- A location change is called only once and constantly monitors the user's current location
Each invocation, the user's latest position (userlocation parameter) is passed in.
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated;
- Called when the map's display area is about to change
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated;
- Called when the display area of the map has changed
Mkuserlocation
Mkuserlocation is actually a PIN model that includes the following properties
@property (nonatomic, copy) NSString *title;
- Title displayed on the Pin
@property (nonatomic, copy) NSString *subtitle;
- Sub-headings displayed on a PIN
@property (readonly, nonatomic) CLLocation *location;
- Location information (where are the pins pinned?)
Set the display of the map
Mkcoordinateregion
MKCoordinateRegion是一个用来表示区域的结构体,定义如下typedefstruct { // 区域的中心点位置 // 区域的跨度} MKCoordinateRegion;
MKCoordinateSpan的定义typedefstruct { // 纬度跨度 // 经度跨度} MKCoordinateSpan;
Pin
- To identify a particular thing in this position.
Basic operation of a PIN
- Add a PIN
(void) Addannotation: (id) annotation;
Add Multiple Pins
(void) Addannotations: (Nsarray *) annotations;
Remove a PIN
(void) Removeannotation: (id) annotation;
Remove multiple Pins
- (void) Removeannotations: (Nsarray *) annotations;
(ID) What is the annotation parameter?
Pin Model object: Data used to encapsulate a pin, such as the position of a pin, title, sub-title, etc.
Pin model
- Create a new PIN model class
#import <MapKit/MapKit.h>@interface MyAnnotation : NSObject <MKAnnotation>/** 坐标位置 */@property (nonatomic, assign) CLLocationCoordinate2D coordinate;/** 标题 */@property/** 子标题 */@property@end
MyAnnotation *anno = [[MyAnnotation alloc] init];anno.title = @"大头针";anno.subtitle = @"大头针大头针";anno.coordinate = CLLocationCoordinate2DMake(40116);[self.mapView addAnnotation:anno];
Custom Pins
How to customize a pin
- Code
-(Mkannotationview *) Mapview: (Mkmapview*) Mapview viewforannotation: (ID<MKAnnotation>) annotation{//Determine the type of annotation if(! [Annotation iskindofclass:[jltuangouannotation class]])return Nil;//Create Mkannotationview Static NSString*id = @"Tuangou"; Mkannotationview *annoview = [Mapview dequeuereusableannotationviewwithidentifier:id];if(Annoview = =Nil{Annoview = [[Mkannotationview alloc] initwithannotation:annotation Reuseidentifier:id]; Annoview. Canshowcallout=YES; }//Transfer model dataAnnoview. Annotation= annotation;//Set PictureMjtuangouannotation *tuangouannotation = annotation; Annoview. Image= [UIImageImagenamed:tuangouannotation. Icon];returnAnnoview;}
Mkannotationview
The pin control on the map is Mkannotationview
Properties of the Mkannotationview
@property (nonatomic, strong) id <MKAnnotation> annotation;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic) BOOL canShowCallout;
- Whether the callout is displayed
@property (nonatomic) CGPoint calloutOffset;
@property (strong, nonatomic) UIView *rightCalloutAccessoryView;
- What controls appear to the right of the callout
@property (strong, nonatomic) UIView *leftCalloutAccessoryView;
- What controls appear to the left of the callout
Mkpinannotationview
Mkpinannotationview is a subclass of Mkannotationview
Mkpinannotationview has 2 more properties than Mkannotationview
@property (nonatomic) MKPinAnnotationColor pinColor;
@property (nonatomic) BOOL animatesDrop;
- Whether the pin was dropped from the sky the first time
Navigation
Navigating the Code:
- (void) Startnavigatewithsorceitem: (Mkmapitem *) SourceItem Destinationitem: (Mkmapitem *) destinationitem{//1. Create an item array Nsarray*items = @[sourceitem, Destinationitem];//2. Create Options /* Mk_extern NSString * Const Mklaunchoptionsdirectionsmodekey Driving mode (drive/walk) mk_extern NSString * Const MKLAUNC Hoptionsmaptypekey Map Type mk_extern NSString * Const MKLAUNCHOPTIONSSHOWSTRAFFICKEY SHOW Traffic conditions * * nsdictionary*options = @{mklaunchoptionsdirectionsmodekey:mklaunchoptionsdirectionsmodewalking, MKLaunc Hoptionsmaptypekey: @ (mkmaptypesatellite), Mklaunchoptionsshowstraffickey: @YES};//3. Open the system map and start navigating[Mkmapitem openmapswithitems:items launchoptions:options];}
Summary Chart
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Map and location