Skip to content

Instantly share code, notes, and snippets.

@edwardinubuntu
Last active November 22, 2016 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwardinubuntu/c32cbcf87efa9e0ca6a9f480d8449fe7 to your computer and use it in GitHub Desktop.
Save edwardinubuntu/c32cbcf87efa9e0ca6a9f480d8449fe7 to your computer and use it in GitHub Desktop.
tibame.com iOS Swift 地圖與定位 - 定位與地圖

定位與地圖

實作一個引用 Location Manager 來取得使用者現在位置,啟動模擬器 Debug > Location > City Bicycle Ride 來持續更新地圖,並且顯示使用者的位置。

完成方式

  • 增加 CoreLocation.framework、MapKit.framework
  • 引用 CLLocationManager
  • 當取得更新位置,配置給地圖
  • 在 Info.plist 增加 NSLocationWhenInUseUsageDescription Current Location
//
// ViewController.swift
// HelloLocation
//
// Created by Edward Chiang on 16/11/2016.
// Copyright © 2016 TKU. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager : CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Get location!")
print("\(locations.first?.coordinate.latitude), \(locations.first?.coordinate.longitude)")
let location = locations.first! as CLLocation
let region = MKCoordinateRegion(center: CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude), span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
mapView.setRegion(region, animated: true)
// manager.stopUpdatingLocation()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment