IOS luge Development notes (5) (Official API for map positioning)

Source: Internet
Author: User

IOS luge Development notes (5) (Official API for map positioning)
Positioning

To implement the map and navigation functions, you must first familiarize yourself with the positioning function and use the Core Location framework in iOS. Core Location can be used independently. It is completely independent from the map development framework MapKit. However, it is often used together with the positioning framework. The Core Location mainly includes the Location and Geographic Encoding (including anti-encoding) functions.

Positioning

Positioning is a very common function. For example, if you allow the software to locate a map software after it is opened, the software is automatically locked to the current position after it is opened, if the user's mobile phone moves, the current location will also change. To implement this function, you need to use the CLLocationManager class in Core Loaction. First, let's take a look at some of the main methods and attributes of this class:

Class Method Description
+ (BOOL) locationServicesEnabled; Whether to enable the location service. If you do not enable the location service, you can be prompted to enable the location service.
+ (CLAuthorizationStatus) authorizationStatus; Locate the service authorization status and return the enumerated type:
KCLAuthorizationStatusNotDetermined: You have not made a decision to enable the location service.
KCLAuthorizationStatusRestricted: The positioning service is not authorized by the user. The user may not be authorized to access the service.
Kclthorizationstatusdenied: the user has explicitly disabled the application to use the location service or the current system location service is disabled.
KCLAuthorizationStatusAuthorizedAlways: The application is authorized to use the location service all the time, even if the application is not in use status.
KCLAuthorizationStatusAuthorizedWhenInUse: allow access to the location service during this application
Attribute Description
DesiredAccuracy Positioning accuracy, enumeration type:

KCLLocationAccuracyBest: the most precise positioning
CLLocationAccuracy kCLLocationAccuracyNearestTenMeters: 10 meters error range
KCLLocationAccuracyHundredMeters: error range of hundreds of meters
KCLLocationAccuracyKilometer: kilometer error range
KCLLocationAccuracyThreeKilometers: 3 km error range

DistanceFilter Minimum distance for Location Information Update. The location information is updated only when the movement is greater than this distance. The default value is kCLDistanceFilterNone. No distance limit is imposed.
Object Method Description
StartUpdatingLocation Start locating and tracing. After locating, the system executes the-(void) locationManager (CLLocationManager *) manager didUpdateLocations (NSArray *) locations according to the update frequency set by the user. The method feedback positioning information
StopUpdatingLocation Stop locating and tracing
StartUpdatingHeading Start navigation direction tracking
StopUpdatingHeading Stop navigation direction tracking
StartMonitoringForRegion: Start to locate and track a region. If you enter or exit a region, you will call-(void) locationManager :( CLLocationManager *) manager.
DidEnterRegion :( CLRegion *) region and-(void) locationManager :( CLLocationManager *) manager
DidExitRegion :( CLRegion *) region proxy method feedback
StopMonitoringForRegion: Stop locating and tracking a region
RequestWhenInUseAuthorization Request to obtain the positioning service authorization when using the application. Note that before using this method, you must configure NSLocationWhenInUseUsageDescription in info. plist.
RequestAlwaysAuthorization Request to obtain the application's permission to use the positioning service. before using this method, configure NSLocationAlwaysUsageDescription in info. plist.
Proxy Method Description
-(Void) locationManager :( CLLocationManager *) manager didUpdateLocations :( NSArray *) locations; Run the command after the location is changed (the command is executed after the location is located for the first time)
-(Void) locationManager :( CLLocationManager *) manager
DidUpdateHeading :( CLHeading *) newHeading;
Run the command after the navigation direction changes.
-(Void) locationManager :( CLLocationManager *) manager
DidEnterRegion :( CLRegion *) region
Run
-(Void) locationManager :( CLLocationManager *) manager
DidExitRegion :( CLRegion *) region
Run the command after exiting a region.

IOS 8 also provides more user-friendly positioning service options. The App's location service is no longer just disabled or opened. Now, the activation of the location service provides three options: "never", "never", and "always 」. At the same time, considering the energy consumption, if an App requires that the positioning service be enabled in the background, iOS 8 will not only ask you when you open the App for the first time, in daily use, a pop-up window will pop up to remind you that the App has been using the location service in the background, and ask if you want to continue to allow. In iOS7 and earlier versions, if you use the location service in an application, you only need to call the startUpdatingLocation method in the application and then ask the user whether to allow the application to use the location service, at the same time, you can go to info. the configuration in plist informs the user of the purpose by configuring Privacy-Location Usage Description. This configuration is optional.
However, the configuration items in iOS8 have changed. You can configure NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription To Tell You The purpose of using the positioning service. Note that this configuration is required, if you do not configure the application, the application cannot use the location service by default. If you open the application, no prompt will be given to open the location service, unless you set the location service for the application after installation. In addition, the requestAlwaysAuthorization or locationServicesEnabled method needs to be requested in the application according to the configuration. Since my machine has been updated to the latest version of iOS8.1, the content below is mainly for iOS8, and friends who use iOS7 need to make some adjustments.

Note:

1. Positioning frequency and positioning accuracy should not be the more accurate the better, depending on the actual situation, because the more accurate the performance consumption, the more electricity consumption.

2. after the location is successful, the (void) locationManager :( CLLocationManager *) manager didUpdateLocations :( NSArray *) locations method is frequently called Based on the settings. This method returns an array of geographic location objects, one CLLocation for each element indicates the geographical location information (including the longitude, latitude, poster, and walking speed). The returned array is because sometimes a location may contain multiple locations.

3. If real-time monitoring is not required after the positioning service is used, the positioning service should be immediately closed to save resources.

4. In addition to the positioning function, CLLocationManager can also call startMonitoringForRegion: to monitor the specified region.

There are two main ways to develop maps in iOS: one is to directly use the MapKit framework for map development, which can be used to precisely control maps; the other method is to directly call the official map application provided by Apple, which is mainly used for some simple map applications (such as filling in the navigation cover) and cannot be precisely controlled. Of course, this section focuses on the former, and the subsequent content will be slightly prompted.

Before using MapKit, You Need To briefly understand some common attributes and methods of the Map Display Control MKMapView in MapKit, as shown in the following table:
Attribute Description
UserTrackingMode Trail type, which is an enumeration:
MKUserTrackingModeNone: No user location tracking is performed;
MKUserTrackingModeFollow: tracks user locations;
MKUserTrackingModeFollowWithHeading: tracks the user location and the user's forward direction;
MapType Map type, which is an enumeration:
MKMapTypeStandard: Standard map. Generally, this map can be used;
MKMapTypeSatellite: Satellite map;
MKMapTypeHybrid: Hybrid map, loading the slowest resource consumption;
UserLocation User location, read-only attribute
Annotations All pins in the current map, read-only attribute
Object Method Description
-(Void) addAnnotation :( id ) Annotation; Add a pin, corresponding to an array of add pins
-(Void) removeAnnotation :( id ) Annotation; Delete a pin, corresponding to the deleted PIN array

-(Void) setRegion :( MKCoordinateRegion) region animated :( BOOL) animated;

Sets the map display area to control the map display range on the current screen.
-(Void) setCenterCoordinate :( CLLocationCoordinate2D) coordinate animated :( BOOL) animated; Set the central point of the map
-(CGPoint) convertCoordinate :( CLLocationCoordinate2D) coordinate toPointToView :( UIView *) view; Convert geographical coordinates (longitude and latitude) to mathematical coordinates (UIKit coordinates)
-(CLLocationCoordinate2D) convertPoint :( CGPoint) point toCoordinateFromView :( UIView *) view; Converts a mathematical coordinate to a geographical coordinate.
-(MKAnnotationView *) dequeueReusableAnnotationViewWithIdentifier :( NSString *) identifier; The pin is extracted from the cache pool, similar to the UITableView for UITableViewCell. It is designed for performance optimization.
-(Void) selectAnnotation :( id ) Annotation animated :( BOOL) animated; Select the specified pin
-(Void) deselectAnnotation :( id ) Annotation animated :( BOOL) animated; Deselect the specified pin.
Proxy Method Description
-(Void) mapView :( MKMapView *) mapView didUpdateUserLocation :( MKUserLocation *) userLocation; Triggered when the user location changes (this method is also triggered when the user location is located for the first time)
-(Void) mapView :( MKMapView *) mapView didUpdateUserLocation :( MKUserLocation *) userLocation; Triggered when the display area changes
-(Void) mapViewDidFinishLoadingMap :( MKMapView *) mapView; Triggered after the map is loaded
-(MKAnnotationView *) mapView :( MKMapView *) mapView viewForAnnotation :( id ) Annotation; Triggered when a pin is displayed and returned to the pin view. You can use this method to customize the pin.
-(Void) mapView :( MKMapView *) mapView didSelectAnnotationView :( MKAnnotationView *) view Triggered when a pin is selected
-(Void) mapView :( MKMapView *) mapView didDeselectAnnotationView :( MKAnnotationView *) view Triggered when the PIN is deselected
-(MKOverlayRenderer *) mapView :( MKMapView *) mapView rendererForOverlay :( id ) Overlay Triggered when rendering a map covering
Set pin View

In some applications, the system's default pin style may not meet the actual needs. In this case, you need to modify the default pin view style. According to the previous MapKit proxy method, it is not difficult to find-(MKAnnotationView *) mapView :( MKMapView *) mapView viewForAnnotation :( id ) Annotation; the method returns a pin view. You only need to implement this method and define a pin view MKAnnotationView object in this method and set relevant attributes to change the default pin view style. MKAnnotationView common attributes:

Attribute Description
Annotation Pin model information, including title, subtitle, and geographical location.
Image Pin pictures
CanShowCallout Click whether the pin displays the title and sub-title content. Note that if you go to-(MKAnnotationView *) mapView :( MKMapView *) mapView viewForAnnotation :( id ) Annotation.
CalloutOffset The offset of the Details View is displayed when you click the pin.
Selected Selected or not
LeftCalloutAccessoryView The Left view of details is displayed.
RightCalloutAccessoryView The view on the Right of details is displayed.

Note:

A. the call time of this proxy method: Whenever a pin is displayed on the System Visual Interface, this method is called to return a pin View to the interface, at the same time, the current system location annotation (that is, the blue position in the MAP) is also a pin and this method is also called. Therefore, you need to treat the pin view differently.

B. Similar to the proxy method of UITableView, this method is called frequently. during development, you need to reuse the cache pool of MapKit to cache the pin view and reuse it.

C. Custom pins do not allow interactions by default. If interactions require canShowCallout = true

D. If the proxy method returns nil, the default pin view will be used, which needs to be set as needed.

Use the built-in map application

In addition to using the MapKit framework for map development and precise control and customization of maps, it is also a good choice to use the map application that comes with apple if there are no special requirements for applications. The MKMapItem class in MapKit is used to use apps that come with Apple. This class has an openInMapsWithLaunchOptions: dynamic method and an openMapsWithItems: launchOptions: static method used to open an apple map application. The first method is used to mark a location on a map. The second method can be used to mark multiple locations and navigate between multiple locations, which is convenient to use. Before getting familiar with the use of these two methods, it is necessary to briefly describe the options parameters in the two methods:

Key (constant) Description Value
MKLaunchOptionsDirectionsModeKey Route mode, constant MKLaunchOptionsDirectionsModeDriving driving mode
MKLaunchOptionsDirectionsModeWalking walking mode
MKLaunchOptionsMapTypeKey Map type, enumeration MKMapTypeStandard: Standard Mode
MKMapTypeSatellite: satellite mode
MKMapTypeHybrid: Mixed Mode
MKLaunchOptionsMapCenterKey Center Coordinate, CLLocationCoordinate2D type  
MKLaunchOptionsMapSpanKey Map Display span, MKCoordinateSpan type  
MKLaunchOptionsShowsTrafficKey Whether traffic conditions are displayed, Boolean  
MKLaunchOptionsCameraKey 3D map effect, MKMapCamera type
Note: This property is available from iOS7 and later, and the previous property is available from iOS6
 

Some beginners are easy to confuse. The following is a simple comparison.

CLLocation: Used to indicate location information, including geographical coordinates, altitude, and other information, included in the CoreLoaction framework.

MKUserLocation: A special pin that indicates the user's current location.

CLPlacemark: the landmark class in the positioning framework, which encapsulates detailed geographical information.

MKPlacemark: similar to CLPlacemark, but in the MapKit framework, MKPlacemark can be created based on CLPlacemark.

 

Related Article

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.