iOS Core note-mapkit Framework-navigation

Source: Internet
Author: User

1, Navigation Introduction:

?了解: navigation, simply speaking, is based on the user-specified location, the route planning, and then according to the user in the process of walking, real-time guidance.

1-1, the iOS navigation implementation scheme:
Programme Detailed Description
Programme I Navigate to the system's map app by passing the location you want to navigate to
Programme II Send a network request to the Apple Server/company server for navigation data, and then manually draw the navigation route
Programme III Use third-party SDK for navigation (Baidu map)

?说明: Usually if you need to manually draw a navigation route, you send a request to the Apple server, get navigation information, and here, only a detailed description of scenario I, Programme II, Programme III will be described separately.

2, the system comes with the Map app navigation:

?了解: 采用逆推法 to enable navigation using the Apple system's own map, the key to this way of navigation is: [MKMapItem openMapsWithItems:导航路线点 launchOptions:启动参数] .

2-1. Detailed steps:
Steps Detailed Introduction Notes
The first step Set the start and end point of the navigation route, geocode the destination address into a Cllplacemark landmark object, create Mkplacemark objects from the Cllplacemark object, and Mkplacemark objects on the map represent each point, The corresponding model is then created according to the Mkplacemark object, namely: Mkmapitem object Mkmapitem
Step Two Set start and end model array, configure open System map app launch parameters Start the map before you apply the preparation work
Step Three Open the system by Mkmapitem to openMapsWithItems:launchOptions: bring your own map to navigate Mkmapitem class method

?重要: Gets the Clplacemark object of the target location by geocoding, then creates the Mkplacemark object based on the Clplacemark object, and then creates the corresponding data model object Mkmapitem object based on the Mkplacemark object, and finally, The data model objects of all navigation routes are wrapped in an array, passed to the system's own map app via the Mkmapitem object's Openmapswithitems:launchoptions: Class method; The system comes with a map app to navigate through the incoming data model objects.

2-2. Supplementary explanation:
    • 1, open the system map application, if not set the startup parameters, the user to enter the system map after the step-by-step self-access navigation information.
    • 2. Mkplacemark inherits from Clplacemark, so a Mkplacemark object can be created by Clplacemark object.
    • 3, through the Mkmapitem Mapitemforcurrentlocation class method can directly get the current user location corresponding to the data model, but need to ask the user to locate the authorization, because it involves locating the user's current location.
    • 4, the nature of navigation using the own map app: is to determine the navigation route to pass the point (Cllplacemark---Mkplacemark), Then convert the Landmark object (Mkplacemark) needed for navigation on the map to the corresponding model (Mkmapitem), and then pass all the models through the Mkmapitem openmapswithitems:launchoptions: Class method is passed to the system Map app so that the specified location can be navigated using the system map.
    • 5, using the System map app to navigate the core class: Mkmapitem, Mkplacemark.
2-3. Sample code:
1.//MARK:-Set the start and end point
2.//1. Set the current position as the start model
3. Mkmapitem *beginitem = [Mkmapitem mapitemforcurrentlocation];
4.
5.//2. Set End point
6. [Self.geocoder geocodeaddressstring:@ "Changsha" completionhandler:^ (Nsarray<clplacemark *> * _Nullable Placemarks, Nserror * _nullable error) {
7.//2.1 Get Landmark Object
8. Clplacemark *clplacemark = [Placemarks firstobject];
9.
10.//2.2 Create Mkplacemark according to Clplacemark
Mkplacemark *endplacemark = [[Mkplacemark alloc] initwithplacemark:clplacemark];
12.
13.//2.3 Create an endpoint model
Mkmapitem *enditem = [[Mkmapitem alloc] initwithplacemark:endplacemark];
15.
//MARK:-Use Mkmapitem to open the system map for navigation
17.//1. Array of starting and ending models
Nsarray *items = @[beginitem, Enditem];
19.
20.//2. Set Startup Parameters
Nsdictionary *dict = @{
Mklaunchoptionsdirectionsmodekey:mklaunchoptionsdirectionsmodedriving,
Mklaunchoptionsmaptypekey: @ (Mkmaptypestandard),
Mklaunchoptionsshowstraffickey: @ (YES)
25.};
26.
27.//3. Open the System map app to navigate
[Mkmapitem Openmapswithitems:items launchoptions:dict];
29.}];
3. Manually draw the navigation route:

?了解: To manually draw a navigation route, you need to send a network request to the Apple server to get a navigation route, and you need to remember the key objects: 导航对象 --- MKDirections .

?重要: The navigation route displayed on the screen is also a covering layer, which operates the overlay on the map, in fact the data model of the overlay; Delete overlay: Remove the overlay data model on the map; add overlay: Add overlay data model on map.

3-1. Detailed steps:
Steps Detailed Introduction Notes
The first step Create a navigation Request object (Mkdirectionsrequest) that holds the starting point model (Mkmapitem), the endpoint model (Mkmapitem) for this navigation in the object, the source of the Mkdirectionsrequest object, The destination attribute is specifically used to save the start and end model Create request
Step Two To create a navigation object by navigating the request object (mkdirections) To create a navigation object
Step Three The Navigation object (mkdirections) calls the Calculatedirectionswithcompletionhandler: method to start sending requests to the Apple server, getting navigation data information Get Navigation data
Fourth Step The data is parsed after getting the navigation data from the Apple Server (note: The navigation data is stored in the response Body Mkdirectionsresponse object), the navigation alignment object array is obtained from the response, the array is traversed to get the navigation alignment object (Mkroute), Add the data model for the render layer you want to display in the navigation alignment object to Mapview Parsing navigation data
Fifth Step Implementation returns the Render layer proxy method to be displayed on Mapview, creating a render layer in the proxy method (Mkpolylinerenderer, Mkcirclerenderer, which is determined by the type of data model added to the Mapview ; Mkpolyline: polyline data Model, Mkcircle: Prototype data model) Return to render Layer
3-2, detailed description of the example diagram:

?说明: Essence: Send request to Apple server, get navigation data, get navigation data essence is navigation alignment object, add render layer data model property in navigation alignment object to Mapview, implement Mapview proxy method, create render layer in proxy method, and set related property. The system automatically adds the rendered layer to the mapview.

3-3. Sample code:
1. #import "ViewController.h"
2. #import <MapKit/MapKit.h>
3.
[Email protected] Viewcontroller () <MKMapViewDelegate>
Map of 5./** * *
[Email protected] (Weak, nonatomic) Iboutlet Mkmapview *mapview;
7./** geocoding */
[Email protected] (Strong, Nonatomic) Clgeocoder *geocoder;
9./** Position Manager Object */
[Email protected] (Strong, Nonatomic) Cllocationmanager *mgr;
11.
[Email protected]
13.
[Email protected] Viewcontroller
15.
16.-(void) Viewdidload {
[Super Viewdidload];
18.
//MARK:-Request Authorization
Self.mgr = [Cllocationmanager new];
if ([Self.mgr respondstoselector: @selector (requestwheninuseauthorization)]) {
[Self.mgr requestwheninuseauthorization];
23.}
24.
//MARK:-Set up a proxy
Self.mapView.delegate = self;
27.}
28.
29.-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *) event{
//MARK:-Start navigation
[Self.geocoder geocodeaddressstring:@ "Changsha" completionhandler:^ (Nsarray<clplacemark *> * _Nullable placemarks , Nserror * _nullable error) {
32.//0. Geocoding failed, returning
if (Placemarks.count = = 0 | | error) {
NSLog (@ "geocoding failed");
return;
36.}
37.
//MARK:-Create a navigation request object
Mkdirectionsrequest *request = [[Mkdirectionsrequest alloc] init];
40.
//MARK:-Set the start point, end point model
42.//1. Starting point model, which uses this method to obtain the data model corresponding to the current point "requires user location authorization"
Mkmapitem *beginitem = [Mkmapitem mapitemforcurrentlocation];
Request.source = Beginitem;
45.
46.//2. Set End point
Clplacemark *ENDCL = Placemarks.firstobject;
Mkplacemark *ENDPL = [[Mkplacemark alloc] INITWITHPLACEMARK:ENDCL];
Mkmapitem *enditem = [[Mkmapitem alloc] INITWITHPLACEMARK:ENDPL];
Request.destination = Enditem;
51.
52.//3. Create a navigation object based on the Mkdirectionsrequest object
Mkdirections *direction = [[Mkdirections alloc] initwithrequest:request];
54.
55.//4. Calculate navigation routes
[Direction calculatedirectionswithcompletionhandler:^ (Mkdirectionsresponse * _nullable response, Nserror * _Nul Lable error) {
57.
. if (Error! = nil) {
NSLog (@ "navigation failed");
60.}
NSLog (@ "%zd", Response.routes.count);
62.
63.//4.1. Traversing the navigation alignment object array, Mkroute: Navigating the Alignment object
[Response.routes enumerateobjectsusingblock:^ (Mkroute * _nonnull obj, Nsuinteger idx, BOOL * _nonnull stop) {
65.//4.2 Add the data model for the rendered layer saved in the navigation alignment object to the Mapview
[Self.mapview AddOverlay:obj.polyline];
67.}];
68.}];
69.}];
70.}
71.
#pragma mark-<MKMapViewDelegate>
73.-(Mkoverlayrenderer *) Mapview: (Mkmapview *) Mapview Rendererforoverlay: (id<mkoverlay>) overlay{
74.//1. Create a polyline render layer
Mkpolylinerenderer *renderer = [[Mkpolylinerenderer alloc] initwithoverlay:overlay];
76.
77.//2. Set polyline render layer related properties
Renderer.linewidth = 10; Polyline Render Layer Line width
Renderer.strokecolor = [Uicolor Greencolor]; polyline Render Layer Polyline color
80.
81.//3. Return to polyline render layer
Renderer return;
83.}
84.
#pragma mark-Lazy loading
86.-(Clgeocoder *) geocoder{
if (_geocoder = = nil) {
_geocoder = [[Clgeocoder alloc] init];
89.}
_geocoder return;
91.}
[Email protected]
4. Important class: 4-1, mkdirectionsresponse-response Body object:
Property name function
Source Navigation start position Model
Destination Navigation End Position Model
Routes An array of navigation alignment objects that hold Mkroute objects in an array
4-2. mkroute-Navigation route object:
Property name function
Name Navigation route Name
Advisorynotices Note, warning information in the navigation route
Distance Navigation route Length (actual physical distance, unit: m)
Polyline The navigation route renders the layer geometry data model (that is, the shape of the rendered layer that corresponds to the data model is a polyline, and in the future when the type data model is added to Mapview, the polyline render layer should be created in the proxy method to return)
Steps An array of multiple walking steps (e.g. "Turn left at the front", "Keep straight", etc., Mkroutestep objects)

?注意: Mkroute is a whole road, and Mkroutestep is every section of the way.

4-3. mkroutestep-Navigation Step object:
Property name function
Instructions Step description (e.g. "Turn left at the front", "Keep straight line", etc.)
TransportType Transportation (driving, walking, etc.)
Polyline The geometric line data model of the route corresponding to the map (composed of many points, which can be plotted on the map)
5. Navigation render layer Effect: 5-1, polyline render layer effect:

Example code :

1. #import "ViewController.h"
2. #import <MapKit/MapKit.h>
3.
[Email protected] Viewcontroller () <MKMapViewDelegate>
Map of 5./** * *
[Email protected] (Weak, nonatomic) Iboutlet Mkmapview *mapview;
7./** geocoding */
[Email protected] (Strong, Nonatomic) Clgeocoder *geocoder;
9./** Position Manager Object */
[Email protected] (Strong, Nonatomic) Cllocationmanager *mgr;
[Email protected]
12.
[Email protected] Viewcontroller
14.
15.-(void) Viewdidload {
[Super Viewdidload];
17.
//MARK:-Set up the agent
Self.mapView.delegate = self;
20.
//MARK:-Request Authorization
Self.mgr = [[Cllocationmanager alloc] init];
if ([Self.mgr respondstoselector: @selector (requestwheninuseauthorization)]) {
[Self.mgr requestwheninuseauthorization];
25.}
26.}
27.
28.-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *) event{
//MARK:-Create a navigation request object
Mkdirectionsrequest *request = [[Mkdirectionsrequest alloc] init];
31.
32.//1. Set up a start data model
Mkmapitem *beginitem = [Mkmapitem mapitemforcurrentlocation];
34.
35.//2. Setting the endpoint data model
[Self.geocoder geocodeaddressstring:@ "Leiyang" completionhandler:^ (nsarray<clplacemark *> * _Nullable placemarks , Nserror * _nullable error) {
37.//3. Create a Mkplacemark object
Clplacemark *ENDCL = Placemarks.firstobject;
Mkplacemark *ENDPL = [[Mkplacemark alloc] INITWITHPLACEMARK:ENDCL];
40.
41.//4. Create an Endpoint data model
Mkmapitem *enditem = [[Mkmapitem alloc] INITWITHPLACEMARK:ENDPL];
43.
44.//5. Set as Request object
Request.source = Beginitem;
Request.destination = Enditem;
47.
//MARK:-Create a navigation object
Mkdirections *direcion = [[Mkdirections alloc] initwithrequest:request];
50.
51.//1. Calculating navigation data
[Direcion calculatedirectionswithcompletionhandler:^ (Mkdirectionsresponse * _nullable response, NSError * _Null Able error) {
53.//2. Error-Proof handling
if (Placemarks.count = = 0 | | error) {
NSLog (@ "Request navigation error");
*. return;
57.}
58.
59.//3. Iterate through an array of navigation alignment objects and add the Polyline rendering layer data model to the Mapview
[Response.routes enumerateobjectsusingblock:^ (Mkroute * _nonnull obj, Nsuinteger idx, BOOL * _nonnull stop) {
61.//4. Add the render layer data model Mapview
[Self.mapview AddOverlay:obj.polyline];
63.}];
64.}];
65.}];
66.}
67.
#pragma mark-<MKMapViewDelegate>
69.-(Mkoverlayrenderer *) Mapview: (Mkmapview *) Mapview Rendererforoverlay: (id<mkoverlay>) overlay{
70.//1. Create a polyline render layer
Mkpolylinerenderer *renderer = [[Mkpolylinerenderer alloc] initwithoverlay:overlay];
72.
73.//2. Setting related properties
Renderer.linewidth = 10;
Renderer.strokecolor = [Uicolor Redcolor];
76.
77.//3. Return to polyline render layer
Renderer return;
79.}
80.
Bayi. #pragma mark-geocoding
82.-(Clgeocoder *) geocoder{
if (_geocoder = = nil) {
_geocoder = [[Clgeocoder alloc] init];
85.}
*. return _geocoder;
87.}
[Email protected]

Sample effect Diagram :

5-2. Round render Layer effect:

Example code :

1. #import "ViewController.h"
2. #import <MapKit/MapKit.h>
3.
[Email protected] Viewcontroller () <MKMapViewDelegate>
Map of 5./** * *
[Email protected] (Weak, nonatomic) Iboutlet Mkmapview *mapview;
7.
[Email protected]
9.
[Email protected] Viewcontroller
11.
12.-(void) Viewdidload {
[Super Viewdidload];
14.
*//MARK:-Set the agent for Mapview
Self.mapView.delegate = self;
17.}
18.
19.-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *) event{
//MARK:-Add a circle rendered layer model
21.//1. Circle Rendered Layer Center point
Cllocationcoordinate2d Center = cllocationcoordinate2dmake (40, 116);
23.
24.//2. Create a circular rendered layer data model
Mkcircle *circle = [mkcircle circlewithcentercoordinate:center radius:1000000];
26.
27.//3. Add to Mapview
[Self.mapview addoverlay:circle];
29.}
30.
#pragma mark-<MKMapViewDelegate>
32./**
33. When you add a data model to Mapview, the method is called to return the corresponding render layer
34.
Map @param Mapview
@param overlay rendered layer model
@return Rendering Layers
38. */
39.-(Mkoverlayrenderer *) Mapview: (Mkmapview *) Mapview Rendererforoverlay: (id<mkoverlay>) overlay{
40.//1. Create a circular render layer
Mkcirclerenderer *renderer = [[Mkcirclerenderer alloc] initwithoverlay:overlay];
42.
43.//2. Setting properties
Renderer.fillcolor = [Uicolor Greencolor];
Renderer.alpha = 0.5;
46.
47.//3. Return round rendered layer
-Return renderer;
49.}
[Email protected]

Sample effect Diagram :

iOS Core note-mapkit Framework-navigation

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.