[iOS/Swift] MapKit - 원하는 곳에 어노테이션을 찍어보자

2023. 10. 1. 18:17·iOS/UIKit&SwiftUI

 

 

 

 

맵뷰에서 선택하는 곳에 어노테이션을 찍어보자

 

 

1. 맵뷰에 탭 제스쳐를 추가한다.

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(mapViewTapped(_ :)))
mapView.addGestureRecognizer(tapGesture)

 

2. sender.location(in: )을 통해 임의로 탭한 위치를 가져온다.

@objc private func mapViewTapped(_ sender: UITapGestureRecognizer) {
    let location: CGPoint = sender.location(in: mainView.mapView)
    let mapPoint: CLLocationCoordinate2D = mainView.mapView.convert(location, toCoordinateFrom: mainView.mapView)
    
    setAnnotation(center: mapPoint)
    
}

 

3. convert

Untitled.png

mapView의 convert 메서드를 이용하여 선택한 위치의 좌표를 얻는다.

IMG_9257.jpg

 

4. 어노테이션 추가하기

func setAnnotation(center: CLLocationCoordinate2D) {
    let region = MKCoordinateRegion(center: center, latitudinalMeters: 1000, longitudinalMeters: 1000)
    mapView.setRegion(region, animated: true) 
    
    let annotation = MKPointAnnotation()
    annotation.coordinate = center
    mapView.addAnnotation(annotation)
    
}

선택 좌표를 중심으로 설정하여 지도를 보여준다.

 

 

 

선택 시 하나의 이전에 선택한 어노테이션은 지우고 선택한 어노테이션만 남기고 싶다면?

선택 위치의 어노테이션을 추가하기 전에 모든 어노테이션을 지워준다!

func removeAllAnotation() {
    let annotations = mapView.annotations
    mapView.removeAnnotations(annotations)
}

'iOS > UIKit&SwiftUI' 카테고리의 다른 글

MapKit CustomAnnotation  (2) 2023.10.10
[iOS/Swift] search bar 에 테두리와 그림자 동시 적용하기 - clipsToBounds  (0) 2023.10.01
[iOS/Swift] MapKit - 위치 권한 설정을 구현해보자!  (1) 2023.10.01
[iOS/Swift] Realm - 백업 및 복구 구현하기  (3) 2023.09.16
[iOS/Swift] Realm - Migration  (1) 2023.09.16
'iOS/UIKit&SwiftUI' 카테고리의 다른 글
  • MapKit CustomAnnotation
  • [iOS/Swift] search bar 에 테두리와 그림자 동시 적용하기 - clipsToBounds
  • [iOS/Swift] MapKit - 위치 권한 설정을 구현해보자!
  • [iOS/Swift] Realm - 백업 및 복구 구현하기
김졀니
김졀니
🍎 iOS 개발
  • 김졀니
    졀니의 개발 공부✨
    김졀니
  • 전체
    오늘
    어제
    • 분류 전체보기
      • iOS
        • Swift
        • UIKit&SwiftUI
        • RxSwift&Combine
        • WWDC
      • Study
        • 🚨 TroubleShooting
        • 🌱 SeSAC
  • 블로그 메뉴

    • 홈
    • Github
  • 인기 글

  • 최근 글

  • 태그

    Drawing Cycle
    wwdc23
    @PropertyWrapper
    Swift
    clipstobounds
    FileManager
    이미지 캐싱
    actor
    ReactorKit
    kingfisher header
    swiftdata
    Realm
    mapkit
    위치 권한
    traits
    동시성프로그래밍
    concurrency
    OperationQueue
    인앱리뷰
    pointfree
    의존성 주입
    layoutIfNeeded
    mainactor
    Sendable
    swift concurrency
    RxSwift
    observable
    displayPriority
    ios
    CLLocation
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
김졀니
[iOS/Swift] MapKit - 원하는 곳에 어노테이션을 찍어보자
상단으로

티스토리툴바