Last active
September 20, 2016 04:38
-
-
Save mosluce/60267edda853ae0c002e932243a429b9 to your computer and use it in GitHub Desktop.
MapKit Demo: 地圖加Annotation以及畫線
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// NewMapKit | |
// | |
// Created by 默司 on 2016/9/20. | |
// Copyright © 2016年 默司. All rights reserved. | |
// | |
import UIKit | |
import MapKit | |
class MapViewController: UIViewController, MKMapViewDelegate { | |
let mapView = MKMapView() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
self.view.addSubview(mapView) | |
self.mapView.frame = self.view.frame | |
//mapview 基本設定 | |
self.mapView.showsUserLocation = true | |
self.mapView.delegate = self | |
//加入兩個annotation | |
let annotationA = MKPointAnnotation() | |
annotationA.coordinate = CLLocationCoordinate2DMake(25.061581, 121.551035) | |
let annotationB = MKPointAnnotation() | |
annotationB.coordinate = CLLocationCoordinate2DMake(25.049335, 121.524728) | |
self.mapView.addAnnotation(annotationA) | |
self.mapView.addAnnotation(annotationB) | |
//加入polyline overlay | |
let polyline = MKPolyline(coordinates: [annotationA.coordinate, annotationB.coordinate], count: 2) | |
self.mapView.add(polyline) | |
} | |
override func viewDidAppear(_ animated: Bool) { | |
super.viewDidAppear(animated) | |
let center = CLLocationCoordinate2DMake(25.052756, 121.543997) | |
let region = MKCoordinateRegionMakeWithDistance(center, 1000, 1000) | |
self.mapView.setRegion(region, animated: true) | |
} | |
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { | |
//繪製AnnotationView | |
if let v = mapView.dequeueReusableAnnotationView(withIdentifier: "Pin") as? MKPinAnnotationView { | |
v.annotation = annotation | |
return v | |
} | |
return MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Pin") | |
} | |
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { | |
//決定如何render overlay | |
let render = MKPolylineRenderer(overlay: overlay) | |
render.strokeColor = UIColor.red | |
render.lineWidth = 3.0 | |
return render | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment