Map and location

Source: Internet
Author: User

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
    • Import Frame

    • Import Primary header file
      #import <CoreLocation/CoreLocation.h>

      • Corelocation Framework Usage Notes
        • The prefix for all data types in the Corelocation framework is CL
        • Using Cllocationmanager objects in corelocation to do user positioning
Cllocationmanager
    • Common operations for Cllocationmanager

      • Start user targeting
        - (void)startUpdatingLocation;

      • Stop user Targeting
        - (void) stopUpdatingLocation;

      • When the Startupdatinglocation method is called, the user's location is started constantly, and the agent's method is called frequently in the middle
        - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;

      • How many meters to locate each time
        @property(assign, nonatomic) CLLocationDistance distanceFilter;

      • Positioning accuracy (the more accurate it consumes)
        @property(assign, nonatomic) CLLocationAccuracy desiredAccuracy;

- (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;

      • Warp latitude

      @property(readonly, nonatomic) CLLocationDistance altitude;

      • Elevation

      @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;

      • Travel speed (unit m/s)

      - (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;

      • Location

      @property (nonatomic, readonly) CLRegion *region;

      • Regional

      @property (nonatomic, readonly) NSDictionary *addressDictionary;

      • Detailed address information

      @property (nonatomic, readonly) NSString *name;

      • Address name

      @property (nonatomic, readonly) NSString *locality;

      • City
    • 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
    • You can set the location and area of the map display by Mkmapview the following methods

      • Set the center point location of the map
        @property (nonatomic) CLLocationCoordinate2D centerCoordinate;
        - (void)setCenterCoordinate:(CLLocationCoordinate2D)coordinate animated:(BOOL)animated;

      • Set the display area of a map
        @property (nonatomic) MKCoordinateRegion region;
        - (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animated;

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
    • Add a PIN
MyAnnotation *anno = [[MyAnnotation alloc] init];anno.title = @"大头针";anno.subtitle = @"大头针大头针";anno.coordinate = CLLocationCoordinate2DMake(40116);[self.mapView addAnnotation:anno];
Custom Pins
    • How to customize a pin

      • Set up a proxy for Mkmapview
      • Implement the following proxy method, which returns the Pin control
        - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;
      • Creates and returns a corresponding PIN control based on the passed in (ID) annotation parameter

      • Use of Proxy methods note

        • If nil is returned, the displayed pin takes the system's default style
        • A blue glowing dot that identifies the user's location, which is also a pin, and when the pin is displayed, the proxy method is also called
        • Therefore, you need to be clear in the Proxy method (ID) The annotation parameter represents a custom pin or a blue glow dot
    • 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;

      • Pin model

      @property (nonatomic, strong) UIImage *image;

      • The picture shown

      @property (nonatomic) BOOL canShowCallout;

      • Whether the callout is displayed

      @property (nonatomic) CGPoint calloutOffset;

      • Offset of the callout

      @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;

      • Pin Color

      @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

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.