大阪市中央区 システムソフトウェア開発会社

営業時間:平日09:15〜18:15
MENU

新アプリ「何処リマインダ」の作成(2) ー MapView ー 現在地Markを表示する(2)

株式会社クローバーフィールドの経営理念
著者:川上洋
公開日:2018/06/09
最終更新日:2018/06/20
カテゴリー:技術情報 雑記

こんにちは。川上です。

おおよそのグッグリ先生たちから教示されている現在地処理の方法に、概ねで定石が提示されています。
なので、今回の現在地処理の流れにも、だいたいには、似たり寄ったりでしょう(多分ね)。

まず、

  
// MARK: === ロケーションマネージャー
    var myLocationManager: CLLocationManager = CLLocationManager()

を作成し、func viewDidLoad()に「現在地を取得する」getCurrentLocation()で処理をするようにします。

   
// MARK: - 現在地を取得する
    func getCurrentLocation(){
        print("---- getCurrentLocation()");

        // 現在地を取得します
        myLocationManager = CLLocationManager()
        myLocationManager.delegate = self
        // 承認されていない場合はここで認証ダイアログを表示します.
        let status = CLLocationManager.authorizationStatus()
        if(status == CLAuthorizationStatus.notDetermined) {
            print("didChangeAuthorizationStatus:\(status)");
            //  ✳️✳️ NSLocationAlwaysUsageDescriptionの時、self.myLocationManager.requestAlwaysAuthorization()
            self.myLocationManager.requestWhenInUseAuthorization()
          }
        
        myLocationManager.desiredAccuracy = kCLLocationAccuracyBest
        myLocationManager.distanceFilter = 100
        myLocationManager.startUpdatingLocation()
    }

CLLocationManagerDelegateを準備すると

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 

で、現在地の locations: が受け取りできます。

実NET網を捕まえれば、実機での現在地が表示されます。

var currentLocation: CLLocationCoordinate2D! //現在地取得用プロパティ

をlocationデータの取得データをプロパティで保持するようにして、

       
 // MARK:  +++  locationデータの取得
        if let location = locations.last {
            // 取得した位置情報の緯度経度
            let latitude = location.coordinate.latitude  //緯度
            let longitude = location.coordinate.longitude //経度
            
            // MARK:  === 現在地のlocations値を保持する
            self.currentLocation = CLLocationCoordinate2DMake(latitude,longitude)
		    
                        // MARK:  === MapViewに現在地を表示する
            self.drawMapView(self.currentLocation)

	}

のdrawMapView()で、現在地を表示するようにしました。

    
// MARK: - MapViewを地点を指定して表示する
    func drawMapView(_ center: CLLocationCoordinate2D)
    {
        mapView.setCenter(center,animated:true)

        // 縮尺を設定
        var region:MKCoordinateRegion = mapView.region
        region.center = center
        region.span.latitudeDelta = 0.02
        region.span.longitudeDelta = 0.02

        mapView.setRegion(region,animated:true)

        // 表示タイプを航空写真と地図のハイブリッドに設定

        mapView.mapType = MKMapType.standard    //2Dマップ
//        mapView.mapType = MKMapType.hybrid      //2D+航空マップ
//         mapView.mapType = MKMapType.satellite  //航空マップ

ではでは。

    上に戻る