[swift] NSTimerでGoogleMAPを常に現在地を中央にするように追跡
目次
NSTimerでGoogleMAPを常に現在地を中央にするように追跡
サンプルコード
*CLLocationで位置情報取得できるようにしていることが前提
class ViewController: UIViewController,GMSMapViewDelegate {
var googleMap : GMSMapView!
var latitude: CLLocationDegrees!
var longitude: CLLocationDegrees!
var iconImage:UIImage!
var selfMarker: GMSMarker!
var timer: NSTimer?
var timerBool:Bool = true
override func viewDidLoad() {
super.viewDidLoad()
iconImage = UIImage(named:"icon.png") //自分のアイコンをカスタマイズ
//GoogleMAP
googleMapInit()
//Timer Start
startTimer()
}
//MARK: Timer
// タイマー開始
func startTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.update(_:)), userInfo: nil, repeats: true)
}
func update(timer: NSTimer) {
//GoogleMAPが取得している位置を取得
if let mylocation = googleMap.myLocation {
latitude = mylocation.coordinate.latitude
longitude = mylocation.coordinate.longitude
googleMapSelfRemark(googleMap)
if timerBool {
//カメラを現在地に
let update = GMSCameraUpdate.setTarget(mylocation.coordinate)
googleMap.moveCamera(update) //アニメーションにするとカクカクするのでアニメーションなしのUpdate
}
}
}
//MARK: GoogleMAP Method /////////
func googleMapInit(){
let width = self.view.frame.width
let height = self.view.frame.height
let camera: GMSCameraPosition = GMSCameraPosition.cameraWithLatitude(latitude,longitude: longitude, zoom: kMapZoom) // カメラを生成
googleMap = GMSMapView(frame: CGRectMake(0, 0, width, height)) // MapViewを生成.
googleMap.mapType = kGMSTypeNormal //MAPtype標準
googleMap.delegate = self
googleMap.camera = camera // MapViewにカメラを追加.
googleMap.myLocationEnabled = true //これがないとGoogleMAPで取得した位置が取得できない
self.view.addSubview(googleMap)//viewにMapViewを追加.
googleMapSelfMarkerCreate()
}
//アイコンを再生成
func googleMapSelfRemark(mapView: GMSMapView){
selfMarker.map = nil //自身のアイコンを消す
googleMapSelfMarkerCreate()
}
//アイコンを追加
func googleMapSelfMarkerCreate(){
selfMarker = GMSMarker()
selfMarker.position = CLLocationCoordinate2DMake(latitude, longitude)
selfMarker.icon = iconImage
selfMarker.map = googleMap
}
//MAPのどこかをタップした時はその場所にカメラを移動し、追跡をOFFに
func mapView(mapView: GMSMapView, didTapAtCoordinate coordinate: CLLocationCoordinate2D) {
timerBool = false //追跡OFF
googleMap.animateToLocation(coordinate) //カメラを現在地に
}
//gesture(ピンチやズームなど)があった際は、追跡をOFFに
func mapView(mapView: GMSMapView, willMove gesture: Bool) {
if gesture {
timerBool = false //追跡OFF
}
}
}
googleMap.myLocationEnabled = trueにするとGoogleMAPが現在地を表示できるようになるので
googleMap.myLocationでcoordinate情報を取得する
Timerで1秒ごとにカメラをGoogleMAPの現在地に移動させているので常に中央に表示しているように見える
ちなみに何か動作した時にはカメラの追跡をやめさせたかったので、timerBoolで追跡したい・したくないを実装している