Tenth chapter: Using Mapkit to develop map services

Source: Internet
Author: User
I. Use of the MAPKIT framework

Mapkit.framework uses the Mkmapview class to represent map controls, and developers can add maps by adding and displaying controls in the application interface.

The common properties of the Mapkitview class are as follows:

(1), @property (nonatomic) Mkmaptype maptype; used to set and return the type of map. This property supports the following

typedef ns_enum (Nsuinteger, Mkmaptype) {
    Mkmaptypestandard = 0, (standard map)
    Mkmaptypesatellite, (satellite map)
    Mkmaptypehybrid, (mixed map)
    Mkmaptypesatelliteflyover ns_enum_available (10_11, 9_0),
    mkmaptypehybridflyover NS _enum_available (10_11, 9_0),
} ns_enum_available (10_9, 3_0) __watchos_prohibited;

(2), @property (nonatomic, getter=iszoomenabled) BOOL zoomenabled; for setting and returning the map to be indented;
(3), @property (nonatomic, getter=isscrollenabled) BOOL scrollenabled; for setting and returning the map to be sliding;
(4), @property (nonatomic, getter=isrotateenabled) BOOL rotateenabled ns_available (10_9, 7_0); for setting and returning whether a map can rotate;
(5), @property (nonatomic) Mkcoordinateregion region; for setting and returning the display area of the map;
(6), @property (nonatomic) cllocationcoordinate2d centercoordinate; for setting and returning the central position of the map;
(7), @property (nonatomic) mkmaprect visiblemaprect; for setting and returning the display area of the map;
(8),-(void) Addannotations: (Nsarray

typedef ns_enum (Nsinteger, Mkusertrackingmode) {
Mkusertrackingmodenone = 0,//the user ' s location is not followed
  mkusertrackingmodefollow,//The map follows the user ' s location
mkusertrackingmodefollowwithheading,//the map fo Llows the user ' s location and Heading
} ns_enum_available (NA, 5_0) __watchos_prohibited;

(13), @property (nonatomic, weak, nullable) ID < mkmapviewdelegate > delegate; Used to specify the delegate object for the map control. The object is responsible for handling the related events of the map control;

The main functions of the Mkmapview class are as follows: (1), display maps, such as Guangzhou maps, (2), provide a variety of display methods, such as standard maps, satellite maps, mixed maps, (3), support map scaling operations, (4), support the marking on the map, such as the Mark Crazy Software Education Center. Also can add complex overlay on the map, (5), locate the mobile phone's current position on the map, (6), can locate on the map by latitude and longitude, address;

The delegate attribute of Mkmapview must be an object to implement the Mkmapviewdelegate protocol, and the corresponding method can be implemented when the Mkmapviewdelegate protocol is implemented; When certain events occur on the Mkmapview control, The delegate object of the control (implementing the Mkmapviewdelegate protocol) will automatically fire the response method and process the specific events that occur on the Mkmapview.

The corresponding method of the Mkmapviewdelegate object is fired when the following event occurs in the Mkmapview control: ①, when the Mkmapview display area changes, ②, when the Mkmapview loads, and when the map data is loaded; ③, When the Mkmapview locates the user's location; ④, when Mkmapview adds annotations, ⑤, when the callout position on the Mkmapview control is changed, ⑥, when the callout on the Mkmapview control is selected or deselected; When the Mkmapview control adds an overlay or displays a overlay; 1, use the Mkmapview control

The

Mkmapview control is in Mapkit.framework, so in order to use the control in iOS applications, two things need to be done: ①, add Mapkit framework for the application, ②, use # in the source files that need to use Mkmapview and related classes Import < Mapkit/mapkit.h >③, importing Mapkit.framework 2, specifying map Display center and display area

#import "ViewController.h" @interface Viewcontroller () <CLLocationManagerDelegate,MKMapViewDelegate> {Cllocat
ionmanager* _locationmanager;
    @end @implementation Viewcontroller-(void) viewdidload {[Super viewdidload]; If the location service is available if ([Cllocationmanager locationservicesenabled]) {//1. Instantiate the location manager _locationmanager = [[Cllo
        Cationmanager alloc] init]; 2.
        Set Agent _locationmanager.delegate = self; 3.
        Positioning accuracy [_locationmanager setdesiredaccuracy:kcllocationaccuracybest];
            4. Request User rights::? Open positioning only in the foreground? In the background can also be positioned, if ([[[[[[[[[Uidevice Currentdevice] systemversion] Floatvalue] >= 8) { [_locationmanager requestwheninuseauthorization];//only open position in foreground}//6.
    Update user location [_locationmanager startupdatinglocation]; }else{NSLog (@ "Unable to use positioning service ...")
    ");
    //Set the display style of the map, set up using the standard map self.mapView.mapType = Mkmaptypestandard;
    Set Map to shrink self.mapView.zoomEnabled = YES; Set up a map to scroll
    self.mapView.scrollEnabled = YES;
    Set the map to rotate self.mapView.rotateEnabled = YES;
    Set display user Current position self.mapView.showsUserLocation = YES;
    Set Agent self.mapView.delegate = self;
Call the method that you implement to set the display location and display area of the map [self locatetolatitude:23.126272 longitude:113.395568]; }-(void) Locatetolatitude: (cgfloat) Latitude Longitude: (cgfloat) longitude{//Set the map center way to set longitude, latitude CLLocationCoordinate2
    D Center = {Latitude,longitude};
    You can also use the following method to set longitude, latitude//center.latitude = latitude;
    Center.longitude = longitude;
    Set the map display range Mkcoordinatespan span;
    Span.latitudedelta = 0.01;
    Span.longitudedelta = 0.01;
    Creates a Mkcoordinateregion object that represents the display center and display range of the map mkcoordinateregion region = {Center,span};
Sets the display center and display range of the current map [Self.mapview setregion:region Animated:yes]; #pragma the method in the mark-mkmapviewdelegate//mkmapviewdelegate protocol that fires this method when the Mkmapview display area will change-(void) Mapview: (Mkmapview *) Mapview regionwillchangeanimated: (BOOL) animated{NSLog (@ "The display area of the map control will change"); //mkmapviewdelegate the method in the protocol that fires when the Mkmapview display area finishes changing-(void) Mapview: (Mkmapview *) Mapview regiondidchangeanimated: ( BOOL) animated{NSLog (@ "Display area of map control complete Change");}//mkmapviewdelegate the method in the protocol that fires when Mkmapview starts loading data-(void) Mapviewwillstartloadingmap: (Mkmapview *) mapview{NSLog (@ "Map control starts loading map data");//mkmapviewdelegate protocol method, This method is fired when Mkmapview finishes loading data-(void) Mapviewdidfinishloadingmap: (Mkmapview *) mapview{NSLog (@ "Map control loading map data complete");// The method in the Mkmapviewdelegate protocol that fires when the Mkmapview load data fails-(void) Mapviewdidfailloadingmap: (Mkmapview *) Mapview Witherror: ( Nserror *) error{NSLog (@ "Map control loading map data error, error message:%@", errors);}//mkmapviewdelegate the method in the protocol that fires when Mkmapview starts rendering the map-(void) Mapviewwillstartrenderingmap: (Mkmapview *) mapview{NSLog (@ "Map control starts rendering map");//mkmapviewdelegate protocol method, This method is fired when the Mkmapview render map completes-(void) Mapviewdidfinishrenderingmap: (Mkmapview *) Mapview fullyrendered: (BOOL) fullyrendered

{NSLog (@ Map control render map complete);} #pragma mark-cllocationmanagerdelegate//Successful acquisition of the location data will trigger the method-(void) LocationmanaGER: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) locations{//Get last location data cllocation* location = [Loc
    Ations Lastobject]; In order to obtain the cllocation of the encapsulated longitude, latitude, altitude, speed, direction and other information NSLog (@ "Longitude:%g, Latitude:%g, Height:%g, Speed:%g, Direction:%g", Location.coordinate.latitude,
Location.coordinate.longitude,location.altitude,location.speed,location.course); The method fired when locating failed-(void) Locationmanager: (Cllocationmanager *) Manager didfailwitherror: (nserror *) error{NSLog (@ "Location failed:%
@ ", error); } @end
2016-06-21 15:47:14.975 Map [489:71,686] The display area of the map control will change
//2016-06-21 15:47:14.976 map [489:71,686] Map Control display area complete change
//2016-06-21 15:47:14.981 Map [489:71,686] The display area of the map control will
change//2016-06-21 15:47:14.982 map [489:71,686] Map control display Area complete change
//2016-06-21 15:47:15.035 map [489:71,686] Map control start rendering map
//2016-06-21 15:47:15.112 map [489:71,686] Map controls start loading map data
//2016-06-21 15:47:20.052 map [489:71,686] Longitude: 40.005, Latitude: 116.406, Height: 47.4084, Speed:-1, Direction:-1
3, the use of iOS 7 new Mkmapcamera

IOS 7 added Mkmapcamera as a map of the "viewpoint", developers can use the Mkmapcamera object in the map to add a point of view, used to simulate from the specified position, the specified height of the map to see some points to add 3D experience for the map.

Use Mkmapcamera on the map as follows: ①, create a Mkmapcamera object, you need to specify the camera's longitude, latitude and overlooking height when creating mkmapcamera; ②, Specifies the Mkmapcamera object for the camera property of the Mkmapview.

#import "ViewController.h" @interface Viewcontroller () {cllocationmanager* _locationmanager;} @end @implementatio
    n Viewcontroller-(void) viewdidload {[Super viewdidload]; If the location service is available if ([Cllocationmanager locationservicesenabled]) {//1. Instantiate the location manager _locationmanager = [[Cllo
        Cationmanager alloc] init]; 2.
        Positioning accuracy [_locationmanager setdesiredaccuracy:kcllocationaccuracyhundredmeters];
            3. Request User rights::? Open positioning only in the foreground? In the background can also be positioned, if ([[[[[[[[[Uidevice Currentdevice] systemversion] Floatvalue] >= 8) { [_locationmanager requestwheninuseauthorization];//only open position in foreground}//4.
    Update user location [_locationmanager startupdatinglocation]; }else{NSLog (@ "Unable to use positioning service ...")
    ");
    //Set the display style of the map, set up using the standard map self.mapView.mapType = Mkmaptypesatellite;
    Set Map to shrink self.mapView.zoomEnabled = YES;
    Set the map to scroll self.mapView.scrollEnabled = YES;
    Set the map to rotate self.mapView.rotateEnabled = NO; Set Display userCurrent position self.mapView.showsUserLocation = YES;

    Call the method that you implement to set the display location and display area of the map [self locatetolatitude:23.126272 longitude:113.395568];
    Cllocationcoordinate2d to = {23.126272,113.395568};
    Cllocationcoordinate2d from = {22.826272,113.295568};
    mkmapcamera* camera = [Mkmapcamera cameralookingatcentercoordinate:to fromeyecoordinate:from eyeAltitude:10];

Self.mapView.camera = camera; }-(void) Locatetolatitude: (cgfloat) Latitude Longitude: (cgfloat) longitude{//Set the map center way to set longitude, latitude CLLocationCoordinate2
    D Center = {Latitude,longitude};
    You can also use the following method to set longitude, latitude//center.latitude = latitude;
    Center.longitude = longitude;
    Set the map display range Mkcoordinatespan span;
    Span.latitudedelta = 0.01;
    Span.longitudedelta = 0.01;
    Creates a Mkcoordinateregion object that represents the display center and display range of the map mkcoordinateregion region = {Center,span};
Sets the display center and display range of the current map [Self.mapview setregion:region Animated:yes]; } @end
second, according to the location of the address 1, address resolution and direction address resolution

Because the iOS map positioning must be based on latitude and longitude to complete, so if you need to locate the program according to the address, you need to first resolve the address to longitude, latitude. Here are the following two basic concepts: (1), address resolution: the ordinary user can read the string address to convert to longitude, latitude, (2), Reverse address resolution: The longitude, latitude converted into a normal string address;

iOS provides clgeocoder for address resolution The tool class provides the following 3 methods for address resolution and direction address resolution:

-(void) geocodeaddressstring: (NSString *) addressstring Completionhandler: (Clgeocodecompletionhandler) completionhandler;//parsing according to the given string address, parsing will cut to the longitude and latitude information corresponding to the address;

-(void) geocodeaddressstring: (NSString *) Addressstring inregion: (clregion *) region Completionhandler: (Clgeocodecompletionhandler) completionhandler;// Parsing according to the given string address will give the longitude and latitude information corresponding to the address. This method specifies a clregion type parameter more than the previous method, which represents parsing within a region, which improves the accuracy of the analytic result;

-(void) Reversegeocodelocation: (Cllocation *) Location Completionhandler: (Clgeocodecompletionhandler) completionhandler;//to resolve the string address according to the specified longitude and latitude address;

Since the above 3 parsing methods are more time-consuming operations, so iOS uses code-fast design for all 3 methods--when address resolution succeeds or reverse address resolution succeeds, the system automatically executes the Third-party parameters of the method: code block, which is a code block in the form of the following:

    nsstring* text;
    Clgeocoder *geocoder;
    [Geocoder geocodeaddressstring:text completionhandler:^ (Nsarray *placemarks, Nserror *error) {

    }];

If parsing occurs incorrectly, the Nserror object encapsulates the error message in the parsing process. If the parse succeeds, the Nserror parameter is nil, and the first nsarray parameter encapsulates the result of address resolution or reverse address resolution. In general, address resolution can result in multiple results-this is because the world is likely to have multiple locations with the same name, but reverse address resolution generally results in only one result-because the address given latitude is usually unique based on the specified longitude.

If the resolution succeeds, the element of the Nsarray collection is a Clplacemark object that represents an anchor point that contains the following properties:

(1), @property (nonatomic, readonly, copy) Cllocation *location;//The read-only property returns a Cllocation-type value that encapsulates the Clplacemark object representing the longitude, Latitude Information (2), @property (nonatomic, readonly, copy) NSString *name;//The read-only property returns the name of the address that Clplacemark represents, (3), @property (Nonatomic, ReadOnly, copy) Nsdictionary *addressdictionary; The read-only property returns a Nsdictionary object that encapsulates the details of the address Clplacemark represents; (4), @property ( Nonatomic, ReadOnly, copy) NSString *isocountrycode;//The read-only property returns the code for the country where the Clplacemark represents the address (5), @property (Nonatomic, ReadOnly, copy) NSString *country;//The read-only property returns the state of the address where Clplacemark is represented; (6), @property (nonatomic, readonly, copy) NSString * postalcode;//the read-only property returns the encoding of the address represented by Clplacemark (7), @property (nonatomic, readonly, copy) NSString *administrativearea;// The read-only property returns the administrative area of the address to which Clplacemark is represented; (8), @property (nonatomic, readonly, copy) NSString *subadministrativearea;// The read-only property returns the subordinate administrative area of the address to which Clplacemark is represented; (9), @property (nonatomic, readonly, copy) NSString *locality;// The read-only property returns the city name of the address that Clplacemark represents, (10), @property (nonatomic, readonly, copy) NSString *sublocality;//The read-only property returnsClplacemark the address of the next class city name; (11), @property (nonatomic, readonly, copy) NSString *thoroughfare;// The read-only property returns the path name of the address represented by Clplacemark (12), @property (nonatomic, readonly, copy) NSString *subthoroughfare;// The read-only property returns the next-level road name for the address represented by Clplacemark;
Address Resolution
self.geocoder_01 = [[Clgeocoder alloc]init];
[Self.geocoder_01 geocodeaddressstring:@ "completionhandler:^, No. 40th, Tian Cun, Haidian District, Beijing" (Nsarray *placemarks, NSError *error) {
    //If the number of binding elements of the analytic result is greater than 0, it indicates that the longitude latitude information if
    (Placemarks.count > 0) {
        ///Only processes an analytic result, the actual project can use the list to let the user choose;
        For (clplacemark* placemark in placemarks) {
            NSLog (@ "Longitude is:%g, Latitude:%g", Placemark.location.coordinate.longitude, placemark.location.coordinate.latitude);
        }
    else{
        NSLog (@ "error =%@", error);
        NSLog (@ "no results");
Reverse Address Resolution
self.geocoder_02 = [[Clgeocoder alloc]init];
cllocation* location = [[Cllocation alloc]initwithlatitude:39.9286 longitude:116.327]; [Self.geocoder_02 reversegeocodelocation:location completionhandler:^ (Nsarray *placemarks, NSError *error) {//If the number of binding elements of the parse result is greater than 0, it indicates that the resolution has the address information if (Placemarks.count > 0) {///processing only one parse result, the actual project can use the list to let the user choose; for (clplacemark* placemark in Placemarks)
            {nsarray* Addrarray = [placemark.addressdictionary objectforkey:@ "Formattedaddresslines"];
            nsmutablestring* addr = [nsmutablestring string];
            for (nsstring* str in addrarray) {[addr appendstring:str];
            } NSLog (@ "%@", placemark.addressdictionary); NSLog (@ "Longitude is:%g, Latitude is:%g, Address:%@", Placemark.location.coordinate.longitude,placemark.location.coordinate.latitude,
        addr);
        }}else{NSLog (@ "error =%@", error);
    NSLog (@ "no results"); }
}];
Longitude is: 116.333, Latitude is: 39.9299, Address: Beijing, China City, Haidian District, No. million Zhuang Street, 22-2 Building

Attention
① and Clgeocoder belong to Corelocation.framework,
Developers need to add corelocation framework to the project
②, use #import < corelocation/corelocation.h > 2 in code using Clgeocoder, location based on address

According to the location of the idea is very simple, as long as the following two steps can be: ①, using Clgeocoder according to the string address to obtain the latitude and longitude of the address, ②, according to the interpretation of the longitude, latitude to locate; Iii. add anchor points to the map

Many times, we want to add anchor points to the map (that is, an icon that displays the details of the location when the user clicks the icon) to identify the important location, just call Mkmapview's addannotation: method to add anchor points to the map. 1. Add simple anchor points

-(void) Addannotation: (id <MKAnnotation>) annotation;

Mkannotation in the above method is a protocol that defines 3 attributes for setting and returning information about an anchor point;

(1), @property (nonatomic, readonly) cllocationcoordinate2d coordinate;//is used to set and return the location of the anchor points. The attribute value must be a CLLOCATIONCOORDINATE2D structure variable, which encapsulates longitude and latitude information,

(2), @property (nonatomic, readonly, copy) NSString *title;// The caption used to set and return anchor points,

(3), @property (nonatomic, readonly, copy) nsstring *subtitle;//subtitle for setting and returning anchor points

iOS provides an implementation class for the Mkannotation protocol: Mkpointannotation, which implements all the mkannotation methods, so you can usually add anchor points using mkpointannotation:

#import "ViewController.h" #import <CoreLocation/CoreLocation.h> @interface Viewcontroller () {Cllocationmanage
r* _locationmanager;
    @end @implementation Viewcontroller-(void) viewdidload {[Super viewdidload]; If the location service is available if ([Cllocationmanager locationservicesenabled]) {//1. Instantiate the location manager _locationmanager = [[Cllo
        Cationmanager alloc] init]; 2.
        Positioning accuracy [_locationmanager setdesiredaccuracy:kcllocationaccuracyhundredmeters];
            3. Request User rights::? Open positioning only in the foreground? In the background can also be positioned, if ([[[[[[[[[Uidevice Currentdevice] systemversion] Floatvalue] >= 8) { [_locationmanager requestwheninuseauthorization];//only open position in foreground}//4.
    Update user location [_locationmanager startupdatinglocation]; }else{NSLog (@ "Unable to use positioning service ...")
    ");
    //Set the display style of the map, set up using the standard map self.mapView.mapType = Mkmaptypesatellite;
    Set Map to shrink self.mapView.zoomEnabled = YES;
    Set the map to scroll self.mapView.scrollEnabled = YES; Set map to rotate SElf.mapView.rotateEnabled = YES;
    Set display user Current position self.mapView.showsUserLocation = YES;
Call the method that you implement to set the display location and display area of the map [self locatetolatitude:23.126272 longitude:113.395568]; }-(void) Locatetolatitude: (cgfloat) Latitude Longitude: (cgfloat) longitude{//Set the map center way to set longitude, latitude CLLocationCoordinate2
    D Center = {Latitude,longitude}; You can also use the following method to set longitude, latitude//center.latitude = latitude;

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.