Easy Map (Mkmapview,cllocationmanagerdelegate,clgeocoder)

Source: Internet
Author: User

Overview

This chapter focuses on the use of location services in iOS, including positioning, maps, map markers, and map positioning. Since the current map development and the previous difference is relatively large, and the map involves relatively complex points, so the experiment time is more, some places still have some problems.


results show


Note that the two digits of the text box is the current latitude and longitude, the map view switch is the location to switch to the latitude and longitude, the last red label is the latitude and longitude in the map, but because of the latitude and longitude resolution part of the problem, so the latitude and longitude of the corresponding address is not displayed. (The example does not use a proxy to resolve the latitude and longitude, using Clgeocoder, because the previously used agent is no longer used.) )


Process Overview

1. Before you start the project, you need to know the main steps: A. Locate the current address B. Resolving longitude and Latitude gets the corresponding address, and then the map view switches to that location C. mark the location on the map

2. Positioning part because see the tutorial older, so the actual operation is different, the latest location needs to increase authorization. The main method is to modify the Info.list file, and then add the authorization code inside the code. As shown below:

/*1.info.plist add two fields that are not in default  nslocationalwaysusagedescription  nslocationwheninuseusagedescription  and set the value to yes*/  //2. Set authorization/Start location before starting positioning-(void) onlocate{    self._textlocationinfo.text = @ "";    Self._locatemanage = [[Cllocationmanager alloc] init];    Self._locatemanage.delegate = self;    Self._locatemanage.desiredaccuracy = kcllocationaccuracybest;    Self._locatemanage.distancefilter = +;       The new version needs to be licensed if ([[[[[    Uidevice Currentdevice] systemversion] doublevalue] > 8.0)    {        [self._locatemanage Requestwheninuseauthorization];    }        [Self._locatemanage startupdatinglocation];    [Self._locateactivityindicator startanimating];}

3. Implement the Protocol of the positioning agent and the map proxy protocol, mainly to complete the following methods:

#pragma implement protocol cllocationmanagerdelegate//Locate the method successfully, the last member in the array is the newest address-(void) Locationmanager: (Cllocationmanager *) Manager     Didupdatelocations: (Nsarray *) locations//Authorization Complete Call this method to view the authorization status-(void) Locationmanager: (Cllocationmanager *) Manager Didchangeauthorizationstatus: (clauthorizationstatus) status;//location failed Call this method-(void) Locationmanager: ( Cllocationmanager *) Manager didfailwitherror: (nserror *) error, #pragma implementation protocol mkmapviewdelegate//draw callout-(Mkannotationview *) Mapview: (Mkmapview *) Mapview viewforannotation: (id <MKAnnotation>) annotation;

4. After successful acquisition of the address, set the map view based on the latitude and longitude in the address, and then use Clgeocoder parse the latitude and longitude address.

5. After resolving the address, you need to mark the current position on the map, you need to create a new class, implement the labeling protocol, specify the latitude and longitude of the label, title and sub-title

6. When finished, stop positioning


Main codeh file

  viewcontroller.h//  findme////  Created by God Lin on 14/12/13.//  Copyright (c) 2014 Arbboter. All rights reserved.//#import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import <corelocation/ Corelocation.h> @interface Viewcontroller:uiviewcontroller <cllocationmanagerdelegate, MKMapViewDelegate> {    mkmapview* _mapview;    uibutton* _buttonlocate;    uitextview* _textlocationinfo;    uiactivityindicatorview* _locateactivityindicator;        Cllocationmanager* _locatemanage;} @property (nonatomic, retain) mkmapview* _mapview; @property (nonatomic, retain) uibutton* _buttonlocate; @property ( Nonatomic, retain) uitextview* _textlocationinfo; @property (nonatomic, retain) uiactivityindicatorview* _ Locateactivityindicator, @property (nonatomic, retain) cllocationmanager* _locatemanage; @end

m file

viewcontroller.m//findme////Created by God Lin on 14/12/13.//Copyright (c) 2014 Arbboter. All rights reserved.//#import "ViewController.h" #import "MapLocation.h" @interface Viewcontroller () @ End@implementation viewcontroller@synthesize _buttonlocate, _locateactivityindicator, _mapView, _textLocationInfo;@    Synthesize _locatemanage;//Interface Control layout-(void) autolayout{cgfloat _x = self.view.frame.origin.x;    CGFloat _y = SELF.VIEW.FRAME.ORIGIN.Y;    CGFloat _w = self.view.frame.size.width;        CGFloat _h = self.view.frame.size.height;    CGFloat Xedge = 10;    CGFloat Yedge = 10;    CGFloat x = _x + Xedge;    CGFloat y = _y + 2*yedge;    CGFloat w = _w-2*xedge;        CGFloat h = 50;        Self._mapview.frame = CGRectMake (x, Y, W, _h-y-yedge-h);    y = self._mapview.frame.origin.y + self._mapview.frame.size.height + Yedge;    H-= 5;    Self._buttonlocate.frame = CGRectMake (x, Y, W/5, h);    Self._buttonlocate.layer.cornerradius = 10; Self._buttonlocate.layer.borderwIdth = 1;    [Self._buttonlocate Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];        [Self._buttonlocate settitle:@ "Locate" forstate:uicontrolstatenormal];    CGFloat Xsameleveledge = 2;    x = x + self._buttonlocate.frame.size.width;    Self._textlocationinfo.frame = CGRectMake (X+xsameleveledge, Y, 4*w/5-xsameleveledge, h);    Self._textlocationinfo.layer.borderwidth = 1;    Self._textlocationinfo.layer.cornerradius = 10;        self._textlocationinfo.editable = NO;    Self._locateactivityindicator.frame = CGRectMake (0,0, h*2, h*2);    [Self._locateactivityindicator Setcenter:cgpointmake (_W/2, _H/2)];    [Self._locateactivityindicator Setactivityindicatorviewstyle:uiactivityindicatorviewstylewhitelarge]; Self._locateactivityindicator.color = [Uicolor blackcolor];}    Start positioning-(void) onlocate{Self._textlocationinfo.text = @ "";    Self._locatemanage = [[Cllocationmanager alloc] init];    Self._locatemanage.delegate = self; Self._locatemanage.desiredaccuracy = kCllocationaccuracybest;       Self._locatemanage.distancefilter = 1000; The new version needs to be licensed if ([[[[[Uidevice Currentdevice] systemversion] doublevalue] > 8.0) {[Self._locatemanage request    Wheninuseauthorization];    } [Self._locatemanage startupdatinglocation]; [Self._locateactivityindicator startanimating];}        -(void) stoplocate{if (self._locatemanage) {[Self._locatemanage stopupdatinglocation];        Self._locatemanage.delegate = nil;        [Self._locatemanage release];        Self._locatemanage = nil;    [Self._locateactivityindicator stopanimating];        }}-(void) viewdidload{[Super Viewdidload];    Self._mapview = [[Mkmapview alloc] init];        [Self.view Addsubview:self._mapview];    Self._buttonlocate = [[UIButton alloc] init];    [Self._buttonlocate addtarget:self Action: @selector (Onlocate) forcontrolevents:uicontroleventtouchupinside];        [Self.view Addsubview:self._buttonlocate]; Self._textlocationinfo = [[Uitextview alloc] InIt];        [Self.view Addsubview:self._textlocationinfo];    Self._locateactivityindicator = [[Uiactivityindicatorview alloc] init];        [Self.view Addsubview:self._locateactivityindicator]; [Self AutoLayout];}    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.}    -(void) dealloc{[_locateactivityindicator release];    [_mapview release];    [_textlocationinfo release];    [_buttonlocate release]; [Super Dealloc];} #pragma implementation protocol cllocationmanagerdelegate-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (    Nsarray *) locations{NSLog (@ "%@", locations);        cllocation* curlocation = [locations Lastobject];    The map is positioned to the current position mkcoordinateregion viewregion = mkcoordinateregionmakewithdistance (curlocation.coordinate, 1000, 1000);    Viewregion = [Self._mapview regionthatfits:viewregion];        [Self._mapview setregion:viewregion Animated:yes]; Parse longitude and latitude as address, add callout on map maplocation* annotation = [[MapLocation alloc] init];    Annotation.coordinate = curlocation.coordinate;    clgeocoder* GeoCoder = [[Clgeocoder alloc] init];    [GeoCoder reversegeocodelocation:curlocation completionhandler:^ (Nsarray *placemarks, Nserror *error)        {if (error) {NSLog (@ "Clgeocoder error,%@", [Error localizeddescription]);            } else {Clplacemark *placemark = [Placemarks lastobject];                                            nsstring* startaddressstring = [NSString stringwithformat:@ "%@%@%@%@%@%@", Placemark.subthoroughfare, Placemark.thoroughfare, Placemark.postalcode, place                                            Mark.locality, Placemark.administrativearea,            Placemark.country];                                    NSLog (@ "Address:%@", startaddressstring);            annotation._city = placemark.locality; Annotation._Country = placemark.country;            Annotation._streetaddrerss = Placemark.thoroughfare;            Annotation._zip = Placemark.postalcode;        Annotation._state = Placemark.name;    }    }];    [Self._mapview addannotation:annotation];        [GeoCoder release]; Set text information nsstring* stringlocation = [[NSString alloc] initwithformat:@ "%@\n%@", Annotation.subtitle, Annotation.title]    ;    Self._textlocationinfo.text = stringlocation;        [Stringlocation release];    [Annotation release]; [Self stoplocate];}    -(void) Locationmanager: (Cllocationmanager *) Manager didchangeauthorizationstatus: (clauthorizationstatus) status{ NSLog (@ "Authorization finished. Status =%d", status);} -(void) Locationmanager: (Cllocationmanager *) Manager didfailwitherror: (nserror *) error{uialertview* alert = [[UI Alertview alloc] initwithtitle:@ "Locate Failed" message:[error description] delegate:nil cancelbuttontitle:@ "OK"    Otherbuttontitles:nil]; NSLog (@ "%@", [Error description]);    [Alert show];    [Alert release];        [Self._locateactivityindicator stopanimating]; [Self stoplocate];} #pragma implementation protocol mkmapviewdelegate//draw Callout-(Mkannotationview *) Mapview: (Mkmapview *) Mapview viewforannotation: (ID < mkannotation>) annotation; {mkpinannotationview* Annotationview = (mkpinannotationview*) [Self._mapview    dequeuereusableannotationviewwithidentifier:@ "Annotationview"]; if (Annotationview = = nil) {Annotationview = [[[Mkpinannotationview alloc] Initwithannotation:annotation reuseId    entifier:@ "Annotationview"] autorelease];    } annotationview.canshowcallout = YES;    Annotationview.pincolor = mkpinannotationcolorred;    Annotationview.animatesdrop = YES; return Annotationview;} @end

(The class that implements the labeling protocol is shown in the project code)


Project Engineering

Easy Map (Mkmapview,cllocationmanagerdelegate,clgeocoder)

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.