MkMapView 사용 방법(swift 버전)

14935 단어 SwiftmapViewiOS
MkMapView를 이용해 지도계 애플리케이션을 만들었지만, 의외로 관련 정보를 수집하지 못했다.나는 그곳에서 간단한 지도 응용 프로그램 제작 절차에 대한 정보를 정리했다.
제작된 응용 프로그램은 Github 위에 놓여 있다.

기능


다음과 같은 기능을 구현했습니다.
*지도에 현재 위치 표시 가능
*위도 경도를 레이블로 표시할 수 있음
* 현재 위치 추적 시작/종료 가능
*지도 확대/축소율 자동 조정 가능
*현재 위치에서 핀으로 고정 가능
*헤드 없이 리드 호출

프로그램 제작 절차

  • 프로젝트 제작
  • 응용 프로그램에서 위치 정보를 사용하는 설정
  • 추가 위치 정보 획득 처리
  • 핀 디스플레이 추가
  • 프로젝트 작성


    참조여기. 프로젝트 작성
  • Single View Application을 선택하여 프로젝트를 만듭니다.
  • 맵 라이브러리(Mackit.framework)를 추가합니다.
  • Storyboard를 사용하여 Map Kit View를 추가합니다.
  • 위치 정보를 표시하는 탭과 위치 정보의 시작, 끝 단추를 추가했습니다.

    응용 프로그램에서 위치 정보 사용 설정


    위치 정보 사용:.plist에 추가합니다.
    * Privacy - Location When In Use Usage Description
    * Privacy - Location Always Usage Description
    이것은 프로그램을 처음 시작할 때 사용자에게 허가를 보낼 때의 정보입니다.
            // 位置情報取得時に、リクエストを出すと
            locationManager!.requestWhenInUseAuthorization()
    
        // このメソッドが呼ばれます
        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            switch status {
            case .notDetermined:
                manager.requestWhenInUseAuthorization()
            case .restricted, .denied:
                break
            case .authorizedAlways, .authorizedWhenInUse:
                break
            }
        }
    

    위치 정보 가져오기 처리 추가


    위치 정보는 CLLocation Manager 클래스를 사용하여 얻을 수 있습니다.
      

    개시하다


    startUpdating Location을 실행합니다.
    위치 정보가 업데이트되면 CLLocation Manager Delegate 프로토콜의 location Manager(CLLoction Manager, didUpdate Locations: [CLLoction])가 호출됩니다.
        @IBAction func tapStartButton(_ sender: UIButton) {
            if locationManager != nil { return }
            locationManager = CLLocationManager()
            locationManager!.delegate = self
            locationManager!.requestWhenInUseAuthorization()
    
            if CLLocationManager.locationServicesEnabled() {
                locationManager!.startUpdatingLocation()
            }
            // tracking user location
            mapView.userTrackingMode = MKUserTrackingMode.followWithHeading
            mapView.showsUserLocation = true
    
        }
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            guard let newLocation = locations.last else {
                return
            }
    
            let location:CLLocationCoordinate2D
                = CLLocationCoordinate2DMake(newLocation.coordinate.latitude, newLocation.coordinate.longitude)
            let latitude = "".appendingFormat("%.4f", location.latitude)
            let longitude = "".appendingFormat("%.4f", location.longitude)
            latLabel.text = "latitude: " + latitude
            lngLabel.text = "longitude: " + longitude
    
            // update annotation
            mapView.removeAnnotations(mapView.annotations)
    
            let annotation = MKPointAnnotation()
            annotation.coordinate = newLocation.coordinate
            mapView.addAnnotation(annotation)
            mapView.selectAnnotation(annotation, animated: true)
    
            // Showing annotation zooms the map automatically.
            mapView.showAnnotations(mapView.annotations, animated: true)
    
        }    
    

    끝맺다


    stop Undating Location을 실행합니다.
            guard let manager = locationManager else { return }
            manager.stopUpdatingLocation()
            manager.delegate = nil
            locationManager = nil
            latLabel.text = "latitude: "
            lngLabel.text = "longitude: "
    
            // untracking user location
            mapView.userTrackingMode = MKUserTrackingMode.none
            mapView.showsUserLocation = false
            mapView.removeAnnotations(mapView.annotations)
    

    풋 뷰


    핀은 MKPoint Annotation 클래스를 사용하는 것을 보여줍니다.
    현재 위치를 하나만 표시하기 위해 모두 삭제하고 추가합니다.
            mapView.removeAnnotations(mapView.annotations)
    
            let annotation = MKPointAnnotation()
            annotation.coordinate = newLocation.coordinate
            mapView.addAnnotation(annotation)
            mapView.selectAnnotation(annotation, animated: true)
    
            mapView.showAnnotations(mapView.annotations, animated: true)
    

    시작 버튼 누르기 전


    초기에는 일본이 전부였다.

    모든 트랙을 표시합니다.
    시작 단추를 눌렀을 때 맵뷰입니다.showAnnotations를 실행하면 모든 트랙이 표시됩니다.
    mapView.setRegion을 사용하여 배율을 지정할 수 있습니다.
            var region:MKCoordinateRegion = mapView.region
            region.center = location
            region.span.latitudeDelta = 0.02
            region.span.longitudeDelta = 0.02
    
            mapView.setRegion(region,animated:true)
    
    또한, 맵뷰.selectAnnotation으로 설정하면 매개변수로 전달된 핀의 호출이 표시됩니다.

    참고 자료

  • Swift와 MapKit로 맵 애플리케이션(전편) 만들기 - koogawa log
  • [Tips] iOS로 위치 정보를 얻는 방법(Swift3.0 지원) - koogawa log
  • [iOS] 위치 정보 가져오기|DevelopersIO
  • MKMapView 핀에 손대지 않고 호출 아웃
  • 아이폰MapKit로 지도 보이기 | 아이폰 앱 개발
  • 좋은 웹페이지 즐겨찾기