More Related Content Similar to 再接再勵學 Swift 程式設計 (20) 再接再勵學 Swift 程式設計4. 學習程式的歷程
學生時期:打電動,沒有日夜的界限
二專畢業:初次接觸 dBase、Lotus 使用 Clipper 做經銷存、應收付帳系統
工作階段1:接觸 Office,開始使用Excel(Lotus)
工作階段2:品保工作,自學圖表、函數、VBA,做出自動化品管系統
興趣展開:自學VB,製作ERP系統,接觸Linux、FreeBSD,自學架設Server
諸葛魔斌誕生
大學時期:半自學 Android App(Java)、C#、iOS App(Swift)
工作轉變:成立諸葛魔斌科技創作室,接案學習,救國團電腦資訊講師
實績:
34. 地圖、導航之程式運用
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var lblLat: UILabel!
@IBOutlet weak var lblLon: UILabel!
@IBOutlet weak var lblHorizontal: UILabel!
@IBOutlet weak var lblAltitude: UILabel!
@IBOutlet weak var lblVertical: UILabel!
@IBOutlet weak var lblDistance: UILabel!
var locationManager: CLLocationManager = CLLocationManager() //取得手機所處地理相關的資訊,包含所在座標
var startLocation: CLLocation!
//CLLocationManagerDelegate,定義了處理CLLocationManager的委外工作,以處理接收地理資訊後的工作
//CLLocationManager:取得資訊後,在委派給實作CLLocationManagerDelegate的物件,以處理取得地理資訊後的工作。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
startLocation = CLLocation(latitude: 22.6138519, longitude: 120.3024543) //目標緯度經度
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
35. 地圖、導航之程式運用
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//定位資訊
let latestLocation: AnyObject = locations[locations.count - 1]
lblLat.text = String(format: "%.4f", latestLocation.coordinate.latitude) //緯度
lblLon.text = String(format: "%.4f", latestLocation.coordinate.longitude) //經度
lblHorizontal.text = String(format: "%.4f", latestLocation.horizontalAccuracy) //水平精度
lblAltitude.text = String(format: "%.4f", latestLocation.altitude) //海拔高度
lblVertical.text = String(format: "%.4f", latestLocation.verticalAccuracy) //垂直精度
let distanceBetween: CLLocationDistance =
latestLocation.distanceFromLocation(startLocation) //計算startLocation與latestLocation距離
lblDistance.text = String(format: "%.2f", distanceBetween) //距離 公尺
}
func locationManager(manager: CLLocationManager,
didFailWithError error: NSError) {
}
}
44. 地圖、導航之程式運用
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var uimap: MKMapView!
var location : CLLocationManager!; //座標管理元件
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
location = CLLocationManager();
//詢問使用者是否同意給APP定位功能
location.requestWhenInUseAuthorization();
//開始接收目前位置資訊
location.startUpdatingLocation();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
45. 地圖、導航之程式運用
override func viewDidDisappear(animated: Bool) {
//因為GPS功能很耗電,所以被敬執行時關閉定位功能
location.stopUpdatingLocation();
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
//取得目前的座標位置
let c = locations[0] as! CLLocation;
//c.coordinate.latitude 目前緯度
//c.coordinate.longitude 目前經度
let nowLocation = CLLocationCoordinate2D(latitude: c.coordinate.latitude, longitude:
c.coordinate.longitude);
//將map中心點定在目前所在的位置
//span是地圖zoom in, zoom out的級距
let _span:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.0005, longitudeDelta: 0.0005);
self.uimap.setRegion(MKCoordinateRegion(center: nowLocation, span: _span), animated: true);
}
}
54. 地圖、導航之程式運用
import UIKit
import MapKit
class ViewController: UIViewController, UISearchBarDelegate, MKMapViewDelegate,
CLLocationManagerDelegate {
@IBOutlet weak var ssearchbar: UISearchBar!
@IBOutlet weak var mapview: MKMapView!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
var locationManager: CLLocationManager! //位置權限、自動更新定位開啟/關閉...
var dest: CLLocationCoordinate2D? //目前導航目標
var drawing: Bool = false //避免多個繪圖動作同時運行
var overlay: MKPolyline? //目前導航路線所在的Overlay
//var handler: (([CLPlacemark]?, NSError) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
55. 地圖、導航之程式運用
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest //精確度
//or locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization() //要求抓取位置的權限
locationManager.startUpdatingLocation() //開始取得定位
//locationManager.distanceFilter = 10
//設定 mapview 和 searchbar
ssearchbar.delegate = self
mapview.delegate = self
mapview.showsUserLocation = true //顯示自己的位置 (藍色點點)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
56. 地圖、導航之程式運用
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
CLGeocoder().geocodeAddressString(searchBar.text!) { (placemarks, error) in
if let coordinate = placemarks?.first?.location?.coordinate {
self.dest = coordinate
searchBar.resignFirstResponder() //隱藏鍵盤
self.drawRoute()
}
}
}
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
print(userLocation.coordinate)
//設置地圖中心位置
mapview.setCenterCoordinate(userLocation.coordinate, animated: true)
//可視範圍 (單位:公尺)
let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 500, 500)
mapview.setRegion(viewRegion, animated: true)
drawRoute()
}
57. 地圖、導航之程式運用
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let render = MKPolylineRenderer(polyline: self.overlay!)
render.strokeColor = UIColor (red: 0.9861, green: 0.2939, blue:0.1098, alpha: 1.0)
render.lineWidth = 3
return render
}
func drawRoute() {
if (drawing) {
return //已經在畫了等等再來 >.=
}
guard let dest = self.dest else {
return //還沒設定目的地...滾!!
}
drawing = true //開始畫了
58. 地圖、導航之程式運用
let req = MKDirectionsRequest()
req.transportType = .Automobile //設定交通類型
//從哪裡出發
req.source = MKMapItem(placemark: MKPlacemark(coordinate: mapview.userLocation.coordinate, addressDictionary: nil))
//要去哪裡
req.destination = MKMapItem(placemark: MKPlacemark(coordinate: dest, addressDictionary: nil))
let directions = MKDirections(request: req)
//計算路徑中...
directions.calculateDirectionsWithCompletionHandler { (res, error) in
if let route = res?.routes.first {
//如果 overlay 已經存在要先移除
if let ol = self.overlay {
self.mapview.removeOverlay(ol)
}
//儲存新的 overlay
self.overlay = route.polyline
self.mapview.addOverlay(route.polyline)
67. 地圖、導航之程式運用
import UIKit
import MapKit
class ViewController: UIViewController, UISearchBarDelegate, MKMapViewDelegate,
CLLocationManagerDelegate {
@IBOutlet weak var ssearchbar: UISearchBar!
@IBOutlet weak var mapview: MKMapView!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var lblLat: UILabel!
@IBOutlet weak var lblLon: UILabel!
@IBOutlet weak var lblHorizontal: UILabel!
@IBOutlet weak var lblAltitude: UILabel!
@IBOutlet weak var lblVertical: UILabel!
@IBOutlet weak var lblDistance: UILabel!
var locationManager: CLLocationManager! //位置權限、自動更新定位開啟/關閉...
var dest: CLLocationCoordinate2D? //目前導航目標
var drawing: Bool = false //避免多個繪圖動作同時運行
var overlay: MKPolyline? //目前導航路線所在的Overlay
68. 地圖、導航之程式運用
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest //精確度
//or locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization() //要求抓取位置的權限
locationManager.startUpdatingLocation() //開始取得定位
//locationManager.distanceFilter = 10
//設定 mapview 和 searchbar
ssearchbar.delegate = self
mapview.delegate = self
mapview.showsUserLocation = true //顯示自己的位置 (藍色點點)
}
69. 地圖、導航之程式運用
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
CLGeocoder().geocodeAddressString(searchBar.text!) { (placemarks, error) in
if let coordinate = placemarks?.first?.location?.coordinate {
self.dest = coordinate
searchBar.resignFirstResponder() //隱藏鍵盤
self.drawRoute()
}
}
}
70. 地圖、導航之程式運用
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
print(userLocation.coordinate)
//設置地圖中心位置
mapview.setCenterCoordinate(userLocation.coordinate, animated: true)
//可視範圍 (單位:公尺)
let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 500, 500)
mapview.setRegion(viewRegion, animated: true)
drawRoute()
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let render = MKPolylineRenderer(polyline: self.overlay!)
render.strokeColor = UIColor (red: 0.9861, green: 0.2939, blue:0.1098, alpha: 1.0)
render.lineWidth = 3
return render
}
71. 地圖、導航之程式運用
func drawRoute() {
if (drawing) {
return //已經在畫了等等再來 >.=
}
guard let dest = self.dest else {
return //還沒設定目的地...滾!!
}
drawing = true //開始畫了
let req = MKDirectionsRequest()
req.transportType = .Automobile //設定交通類型
//從哪裡出發
req.source = MKMapItem(placemark: MKPlacemark(coordinate: mapview.userLocation.coordinate, addressDictionary: nil))
//要去哪裡
req.destination = MKMapItem(placemark: MKPlacemark(coordinate: dest, addressDictionary: nil))
let directions = MKDirections(request: req)
72. 地圖、導航之程式運用
//計算路徑中...
directions.calculateDirectionsWithCompletionHandler { (res, error) in
if let route = res?.routes.first {
//如果 overlay 已經存在要先移除
if let ol = self.overlay {
self.mapview.removeOverlay(ol)
}
//儲存新的 overlay
self.overlay = route.polyline
self.mapview.addOverlay(route.polyline)
//更新文字部分
self.distanceLabel.text = "估計距離:(route.distance/1000)km"
//self.timeLabel.text = "估計時間:(route.expectedTravelTime/3600)hr"
self.timeLabel.text = "估計時間:(route.expectedTravelTime/60)min"
}
self.drawing = false //畫完了
}
}
73. 地圖、導航之程式運用
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//定位資訊
let latestLocation: AnyObject = locations[locations.count - 1]
lblLat.text = "緯度:" + String(format: "%.4f", latestLocation.coordinate.latitude) //緯度
lblLon.text = "經度:" + String(format: "%.4f", latestLocation.coordinate.longitude) //經度
lblHorizontal.text = "水平精度:" + String(format: "%.4f", latestLocation.horizontalAccuracy) //水平精度
lblAltitude.text = "海拔高度:" + String(format: "%.4f", latestLocation.altitude) //海拔高度
lblVertical.text = "垂直精度:" + String(format: "%.4f", latestLocation.verticalAccuracy) //垂直精度
lblDistance.text = self.distanceLabel.text //距離 公尺
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
}
}
75. 地圖、導航之程式運用
結論: 1. 地圖套件引入
2. 元件(物件)、變數(常數)必先宣告
3. 元件(物件)、變數(常數)命名規則 駝峰式
6. 學習階段,務必一字一字『抄』,切勿『複製貼上』
7. 大膽嘗試,好奇無罪
8. 不怕失敗,學習除錯
9. 勇於分享
4. 權限設定
5. 地圖設定
77. 第四、五次聚會學習課程
Android App 入門第一步
iOS Swift 接力使力之玩 Open Data
學習不能中斷,卡關不要氣餒,
讓我們的熱血繼續揮撒在程式的樂趣吧!!
帶著你的筆電,和我們一起享受Coding Fun
註:我們學習的是多系統,所以筆電最好是Macbook哦!
日期:8/10(星期三) 18:30~21:30 Android App 入門第一步
8/17(星期三) 18:30~21:30 iOS Swift 接力使力之玩 Open Data
地點:高雄市前鎮區一心二路157號10樓之4(微盛科技)
捷運三多商圈站4號出口,步行約10分鐘
歡迎踴躍報名,也歡迎高手協助指導
費用:0元(珍惜學習資源)