Map (Swift)

Source: Internet
Author: User

Basic use of a map 1 maps need to rely on the framework: MAPKIT2 Framework Basic role: used for map display, such as pin, route, overlay display, etc. (emphasis on interface display) 3 Use Step:--> 3.1 Import header file: Imports Mapkit (Swift); #import-3.2 Mapkit has a more important UI control: Mkmapview, specifically for map display 4 Setting the map display Type-4.1 map styles can be set manually, 3 before iOS9.0, and 2 added after iOS9.0
        Standard :普通地图        Satellite : 卫星云图        Hybrid : 普通 + 卫星云图        SatelliteFlyover ios9.03D立体        HybridFlyover ios9.03D立体混合
--4.2 Setting mode
mapView.mapType.HybridFlyover
5 Set the control of the map (including: rotation of the map, zoom, move, and so on can be turned on or off)--5.1 settings:
        false//滚动        false//旋转        false//缩放   缩放和滚动默认是有的        false//3D
6 Set the display items of the map (including: Compass on the map, scale bar, buildings, poi points can be controlled for display)--6.1 settings:
 if   #available (IOS 9.0, *) { Mapview.showscompass = true //show compass  mapview.showsscale = true  //display scale bar  mapview.showstraffic = true  //Show traffic } mapview.showsbuildings = true  //show buildings  mapview.showspointsofinterest = true  //show points of interest  mapview.showsuserlocation = true  //display user   
7 common problems when testing--7.1 Why does the map load not show? Answer: Check to see if the network is unobstructed--7.2 why is the map too much of a lattice, forbidden to browse? Answer: Normal, for security and other reasons, do not look too detailed--7.3 Why does the map run up to the memory of the app is very large? Answer: Normal, the map loads a lot of resources 8 the environment required for testing--8.1 Loading map data requires networking--8.2 Xcode version based on the test to choose a different version (iOS9.0 can only use XCode7.0 version)--8.3 iOS system version according to the test Try selecting a different version (for example, the map type, after iOS9.0) 9 map shows the user's location and 9.1 can be set to display the user's current location, as a blue dot on the map (note: If you want to display the user location, after iOS8.0, Need to proactively request user authorization)--9.2 settings: (Two types)
//1. 显示用户的位置后,地图并不跟着用户的位置的改变而改变视角        true//显示用户        //2. 显示用户的位置之后,地图会跟随着用户的位置,一直让用户的位置显示在地图的中心,当时不灵活        mapView.userTrackingMode = .FollowWithHeading
--9.3 Two ways to show the effect: one effect: a blue dot will be displayed on the map to identify the user's location; The map does not scale, and the map does not move with the user's location when the user's position is moved; Mode two effects: a blue dot will be displayed on the map to identify the user's location; And the map zooms to the appropriate scale, showing the user's location, and when the user position is moved, the map will move with the user's location; But sometimes the failure .--> 9.4 test may occur when the problem: the user location does not display?—-> 9.5 Possible reasons: 1> Check the code, whether there are settings to display the user location, whether there is a request location authorization 2> See if the simulator has location information 3> Emulator problem Two user Location tracking 1 Drag a realistic map UI control in storyboard 2 directly in storyboard set up Proxy 3 Import Framework 4 implement Proxy method 5 specific Code:--> 5.1 lazy Load
//懒加载    privatevar location : CLLocationManager = {       let location = CLLocationManager()        if#available(iOS 8.0, *) {            location.requestAlwaysAuthorization()        }        return location    }()
-5.2 Maps Related settings
override func viewDidLoad() {        super.viewDidLoad()        mapView.showsBuildings = true        #available(iOS 9.0, *) {            mapView.mapType.HybridFlyover        }        mapView.mapType.Standard        mapView.showsUserLocation = true        _ = location        mapView.userTrackingMode.FollowWithHeading    }
--5.3 Proxy method
Extension Viewcontroller:mkmapviewdelegate {//When the map gets to the user's location, the callback uses this methodFunc Mapview (Mapview:mkmapview, didupdateuserlocation userlocation:mkuserlocation) {//mkuserlocation Big Head data Model just follow the mkannotation is the PIN data model        //Get the PIN data model of the userUserlocation.title ="Xiaofeng"Userlocation.subtitle ="How are you?????"        //Get the user's current central location         LetCenter = userlocation.location?. Coordinate Mapview.setcentercoordinate (center!, animated:true)//Change the display area         Letspan = Mkcoordinatespanmake (0.162493481087147,0.10857004327103) LetRegion = Mkcoordinateregionmake (center!, span) mapview.setregion (region, animated:true)    }//The method is called when the region changesFunc Mapview (Mapview:mkmapview, regiondidchangeanimated animated:bool) {print (MapView.region.span)}}
6 details of the PIN data model--6.1 mkuserlocation: called the "pin (data) model" (it is essentially a data model, but this model follows the protocol (mkannotation) that the pin follows)- 6.2 Important attributes: Location: The user's current position information (Cllocation object); Title: Pin Callout To display the caption (NSString object); Subtitle: A PIN labels the subheadings (NSString objects) to be displayed. 7 Problems that may occur when testing-7.1 Why don't the blue dots on the map show? Answer: (1) Determine if the code is wrong (for example, whether the user location is displayed); (2) Determine whether the simulator set the position; (3) Look where it is, isn't it? After the current map display area--7.2 map span settings, the final displayed span and setting values are inconsistent. Answer: Because the earth is not a square, with the user's position to move, will automatically correct the map span, keep the map does not deform; three-pin use 1 pin theory: According to the MVC principle--1.1 on the map to manipulate the pin, is actually the data model of the control pin and 1.2 Adding a PIN is adding a PIN data model--1.3 Deleting a PIN is deleting a PIN data Model 2 need to implement function (simple)

3 defining models (must comply with Mkannotation protocol)-3.1 creating model files that comply with Mkannotation

--3.2 Properties required in this model
import MapKitclass XFJAnnotation: NSObject , MKAnnotation {    //位置坐标    var coordinate : CLLocationCoordinate2D = CLLocationCoordinate2DMake(00)    //标题和子标题    varString?    varString?}
-3.3 Get the map in storyboard by dragging the line
//拿到地图    weakvar mapView: MKMapView!
-3.4 Click on the screen to get
//TAP screen to get    OverrideFunc Touchesbegan (touches:set<uitouch>, witheventEvent: Uievent?) {//Get points         LetPoint = Touches.first?. Locationinview (Mapview)//Convert the point you are trying to into longitude and latitude         LetCoodinate = Mapview.convertpoint (point!, Tocoordinatefromview:mapview)//Add a PIN         Letannotation = addanntation (coodinate, title:"Xiaofeng", subtitle:"Hey!!!")//Anti-geocoding for more information         LetLocation = Cllocation (Latitude:coodinate.latitude, Longitude:coodinate.longitude) geoc.reversegeocodelocation (Loc ation) {(CLPLC: [Clplacemark]?, Error:nserror?), Voidinch            //Check whether the content is emptyGuard LetCLPLC = CLPLCElse{return} Guard LetClplcs = Clplc.firstElse{return}//Set the title and sub-title of the pinAnnotation.title = clplcs.locality Annotation.subtitle = clplcs.name}}
-3.4 Mobile screen Remove all pins
//移动屏幕移除所有的大头针   overrideevent: UIEvent?) {        //取出所有的大头针        let annotation = mapView.annotations        //移除有所的大头针        mapView.removeAnnotations(annotation)    }
-3.5 Create a pin with one method
/// MARK:-Create pin  extension Viewcontroller {private  func addanntation  (coordinate:cllocationcoordinate2d, title:string, subtitle:string?)->xfjannotation {        //create a pin         let  annotation = xfjannotation () //set title         Annotation.title = Title Annotation.subtitle = Subtitle //set the position of the pin  annotation.coordinate = coordinate //Add pin  mapview.addannotation (annotatio N) //return pin  return  annotation}}
4 problems that may occur--4.1 anti-geocoding cannot get the corresponding data? Reason: (1) Check whether there is a network (2) Check the code is wrong (3) Sometimes there is no anti-geocoding results in some places, another point to try, if not, to exclude this cause four pins add and remove 1 when the code executes to the following sentence, a proxy method is invoked
//添加大头针        /*        当创建一个大头针数据模型添加到地图上之后,会执行对应的代理方法,在代理方法中查找对应的大头针视图        */        mapView.addAnnotation(annotation)
--1.1 called Proxy methods (PIN related settings)
Extension Viewcontroller:mkmapviewdelegate {//When adding a PIN data model, the method is called, looking for the corresponding PIN view and returning if nil is returned here, representing the system default PINFunc Mapview (Mapview:mkmapview, Viewforannotation annotation:mkannotation), Mkannotationview? {//Create Identity         LetPinid ="Pinid"        //Remove pin view from the cache pool by identity        varPinanntationview = Mapview.dequeuereusableannotationviewwithidentifier (Pinid) as? Mkpinannotationview//Determine if the pin is empty        ifPinanntationview = = Nil {Pinanntationview = Mkpinannotationview (annotation:annotation, Reuseidentifier:pinid )        }//Set the data model (must be set)Pinanntationview?. annotation = annotation//Run a bullet boxPinanntationview?. Canshowcallout =true        //Set the color of the pinPinanntationview?. Pintintcolor = Uicolor.redcolor ()//Set drop animation for pinsPinanntationview?. Animatesdrop =true        //Drag pin top viewPinanntationview?. Draggable =true        //Return PIN view        returnPinanntationview}
--1.2 is called when you drag or select a PIN (both proxy methods)
//call  func  {p Rint (Newstate.rawvalue,oldstate.rawvalue) } //is called when a PIN is selected  func mapview (Mapview:mkmapview, Didselectannotationview View:mkannotationview)  {print ( "selected \ (view.annotation!. title) "" } //callback with  func MAPVI EW (Mapview:mkmapview, Diddeselectannotationview View:mkannotationview)  {print ( "uncheck \ (view.annotation?. title) ") } 
Five pin avatar settings (left and right avatar settings) 1 get a pin set directly in the first proxy method
//PIN to the left view         LetImage = UIImage (named:"Snip20160508_1") LetImageView = Uiimageview (Frame:cgrectmake (0,0, -, -)) Imageview.image = Image Pinanntationview?. Leftcalloutaccessoryview = ImageView//PIN to the right view         LetImage1 = UIImage (named:"Snip20160508_2") LetImageView1 = Uiimageview (Frame:cgrectmake (0,0, -, -)) Imageview1.image = Image1 Pinanntationview?. Rightcalloutaccessoryview = ImageView1
Position tracking of six pins 1 the picture after the execution of the program (red marked part)

2 Code: Mkusertrackingbarbuttonitem (mainly this sentence)
override func viewDidLoad() {        super.viewDidLoad()        let userTrackingItem = MKUserTrackingBarButtonItem(mapView: mapView)        navigationItem.rightBarButtonItem = userTrackingItem        _ = location    }
Summary 1 This blog I simply explained the basic use of the map, the specific implementation of the scene I have to write a map on the application of the specific implementation, will be introduced in the follow-up for you. (The above content is only for beginners to learn, of course, if you have a long history of development experience, trouble you a lot of advice). 2 Finally, if you think that my blog is OK, please pay more attention to my official blog, thank you!!!!

Map (Swift)

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.