Component:
Highlight function:
Google map 所需之 map view 宣告及使用方法:
var myMapView: GMSMapView!
myMapView = GMSMapView(frame: CGRect(x: 0,
y: 0,
width: screenSize.width,
height: screenSize.height))
myMapView.mapType = .normal
myMapView.camera = GMSCameraPosition(target: defaultCenter, zoom: 1, bearing: 0, viewingAngle: 0)
為了讓開啟 app 後會有定位的動畫(從隨意地點滑動到當前地點),這邊使用 defaultCenter 來自定一隨意座標點:
let defaultCenter = CLLocationCoordinate2D(latitude: -32.725757, longitude: 21.481987)
透過 CLLocationManagerDelegate 更新定位地點:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let currentLocation: CLLocation = locations[0] as CLLocation
print("Current Location: \(currentLocation.coordinate.latitude), \(currentLocation.coordinate.longitude)")
if let location = locations.first {
CATransaction.begin()
CATransaction.setValue(Int(2), forKey: kCATransactionAnimationDuration)
myMapView.animate(toLocation: location.coordinate)
myMapView.animate(toZoom: 12)
CATransaction.commit()
myLocationMgr.stopUpdatingLocation()
}
}
上述中的 CATransaction 是為了產生動畫效果,其格式如下:
CATransaction.begin()
CATransaction.setValue(Int(2), forKey: kCATransactionAnimationDuration)
// the code required for animation
CATransaction.commit()
Additional:
此 demo 雖使用了 google map 所提供的圖資,但定位功能仍然是使用 iOS 原生提供的 CLLocationManager,因此在使用定位功能時仍需要跟使用者要求相關的權限,其方法與前篇一樣。
Reference:
Source code on Github
Google Map Api