-
[iOS] #5 Naver 지도 API 내 위치 찾기 & Marker 이미지 변경ToyProject 2023. 6. 21. 01:14
저번 게시글에 이어서 내 위치를 찾아서 마커로 찍어보고 마커 이미지까지 변경해보는 작업을 해보겠슴니당! 아래는 저번 게시글 참조!
https://org9899.tistory.com/148
1. 내 위치 찾아서 마커로 찍어보기
내 위치를 찾기 위해 CoreLocation을 이용할것이다!
https://dongminyoon.tistory.com/1
[iOS] Core Location 사용 위치 정보 얻기
이번에 공모전을 준비하며 개발을 하다보니 iPhone을 기반으로 위치를 얻어와서 지도에 표시해야하는 작업이 있었어요. 찾아 보니, iOS 기본 Framework에서 제공하는 기능이 있더라구요‼️ 기본으
dongminyoon.tistory.com
Core Location이란 내 폰의 위치를 얻어올 수 있는 기능들을 제공해주는 Framework라고 생각해주면 좋다!
Core Location의 기능을 사용하기 위해서 CLLocationManager이라는 클래스를 꼭 사용해주어야한다,,!
Core Location을 사용하기 위해서는 Info.plist에서 위치 권한을 허용해주는게 필수 작업이다!
위 작업은 우리가 흔히 보는 위치 허용을 위한 팝업창을 띄우는거라고 볼 수 있당
아래와 같이 작성해준다!
var locationManager = CLLocationManager() var currentLocation:CLLocationCoordinate2D! var findLocation:CLLocation! var longitude_HVC = 0.0 var latitude_HVC = 0.0
우선 함수를 두개 지정해줄것이다. 아래는 위치에 대한 권한이 있는지 없는지를 확인하는 정확도를 검사해주는 함수이다,,!
private func requestAuthorization() { //정확도 검사 locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters //앱 사용할때 권한요청 switch locationManager.authorizationStatus { case .restricted, .denied: print("restricted n denied") locationManager.requestWhenInUseAuthorization() case .authorizedWhenInUse, .authorizedAlways: print("권한있음") locationManagerDidChangeAuthorization(locationManager) default: locationManager.startUpdatingLocation() print("default") } locationManagerDidChangeAuthorization(locationManager) if(latitude_HVC == 0.0 || longitude_HVC == 0.0){ print("위치를 가져올 수 없습니다.") } }
또한, 아래는 해당 위치를 미리 선언해둔 변수에 저장하는 작업이당,,,!
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { if manager.authorizationStatus == .authorizedWhenInUse || manager.authorizationStatus == .authorizedAlways { if let currentLocation = locationManager.location?.coordinate{ print("coordinate") longitude_HVC = currentLocation.longitude latitude_HVC = currentLocation.latitude } } else{ print("else") } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last { latitude_HVC = location.coordinate.latitude longitude_HVC = location.coordinate.longitude } }
이제 아래와 같이 Viewdidload 함수에 작성해주면 위치를 찾을 수 있게된다,,!
// delegate 설정 locationManager.delegate = self // 사용자에게 허용 받기 alert 띄우기 self.locationManager.requestWhenInUseAuthorization() requestAuthorization() // 내 위치 가져오기 locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation()
근데 위치만 찾을게 아니라, 위치를 찾고 그 위치로 카메라를 이동한 후에 마커를 찍는 작업이 내가 하고싶은 작업이었다!
let cameraPosition = NMFCameraPosition()
이에 카메라 포지션을 잡아주는 함수를 이용해주고, 아래와 같이 위도, 경도를 가져와준다.
// 위도, 경도 가져오기 let latitude = locationManager.location?.coordinate.latitude ?? 0 let longitude = locationManager.location?.coordinate.longitude ?? 0
아래는 추가 기능인데 그냥 참고해두면 좋다! (줌이랑 스크로를 가능하게 지정해두었당,,,!)
mapView.allowsZooming = true // 줌 가능 mapView.allowsScrolling = true // 스크롤 가능
아래와 같이 카메라를 업데이트해주고, 내 위치좌표를 찍어주면 화면을 켰을때 내 위치로 줌이 잡히는것을 볼 수 있다!
let cameraUpdate = NMFCameraUpdate(scrollTo: NMGLatLng(lat: latitude, lng: longitude), zoomTo: 15.0) mapView.moveCamera(cameraUpdate) cameraUpdate.animation = .easeIn
2. 마커 이미지 변경
마커를 등록하고 이미지를 변경하는건 귀찮으니까 한번에 적어보도록하자,,,
설명을 간단하게 하자면, 마커 변수를 추가해주고,
받아온 위도, 경도를 입력해준다.
저 iconImage가 마커 이미지를 변경해주는 작업인데, 난 아래의 me를 그냥 asset파일에 저장해두었당
이어커 마커 핸들러까지 소개하자면, 마커를 클릭하면 아래와 같이 주소가 떠야했기에 마커 클릭시 핸들러까지 추가해주었다,,!
생각보다 간단하즁~? 히히
// 마커 let new_marker = NMFMarker() new_marker.position = NMGLatLng(lat:latitude,lng: longitude) new_marker.iconImage = NMFOverlayImage(name: "me") new_marker.width = 40 new_marker.height = 40 new_marker.touchHandler = { (overlay: NMFOverlay) -> Bool in if self.addressView.isHidden { new_marker.width = 50 new_marker.height = 50 self.addressView.isHidden = false return true // 이벤트 소비, -mapView:didTapMap:point 이벤트는 발생하지 않음 } else { new_marker.width = 40 new_marker.height = 40 self.addressView.isHidden = true return false // 이벤트 넘겨줌, -mapView:didTapMap:point 이벤트가 발생할 수 있음 } } new_marker.mapView = mapView
위와 같이 작업해주면, 화면에는 다음처럼 뜨는것을 확인해줄수있다,,! (나는 시뮬레이터 위치 등록을 안해두어서 그냥 내 폰에 테스트앱을 설치해서 확인해보았다,,,!)
나는 참고로 군자역에 있당,,,,ㅎ허ㅓ허ㅓ,,,,
[전체코드]
// // ViewController.swift // CleanDining // // Created by 김민경 on 2023/06/20. // import UIKit import NMapsMap import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate{ var locationManager = CLLocationManager() let cameraPosition = NMFCameraPosition() var currentLocation:CLLocationCoordinate2D! var findLocation:CLLocation! let geocoder = CLGeocoder() var longitude_HVC = 0.0 var latitude_HVC = 0.0 @IBOutlet weak var addressText: UILabel! @IBOutlet weak var addressView: UIView! override func viewDidLoad() { super.viewDidLoad() let mapView = NMFMapView(frame: view.frame) mapView.allowsZooming = true // 줌 가능 mapView.allowsScrolling = true // 스크롤 가능 mapView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 110, right: 0) // 컨텐츠 패딩값 (하단 탭바만큼 패딩값) view.addSubview(mapView) view.addSubview(addressView) // addressView 모서리를 둥글게 설정 addressView.layer.cornerRadius = 20 addressView.layer.masksToBounds = true addressText.text = "서울특별시 강서구 등촌로13길 13, 1층 (화곡동)" addressText.numberOfLines = 0 // 줄 수를 0으로 설정하면 텍스트가 필요한 만큼 자동으로 줄 바꿈 // delegate 설정 locationManager.delegate = self // 사용자에게 허용 받기 alert 띄우기 self.locationManager.requestWhenInUseAuthorization() requestAuthorization() // 내 위치 가져오기 locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() // 위도, 경도 가져오기 let latitude = locationManager.location?.coordinate.latitude ?? 0 let longitude = locationManager.location?.coordinate.longitude ?? 0 let cameraUpdate = NMFCameraUpdate(scrollTo: NMGLatLng(lat: latitude, lng: longitude), zoomTo: 15.0) mapView.moveCamera(cameraUpdate) cameraUpdate.animation = .easeIn // 마커 let new_marker = NMFMarker() new_marker.position = NMGLatLng(lat:latitude,lng: longitude) new_marker.iconImage = NMFOverlayImage(name: "me") new_marker.width = 40 new_marker.height = 40 new_marker.touchHandler = { (overlay: NMFOverlay) -> Bool in if self.addressView.isHidden { new_marker.width = 50 new_marker.height = 50 self.addressView.isHidden = false return true // 이벤트 소비, -mapView:didTapMap:point 이벤트는 발생하지 않음 } else { new_marker.width = 40 new_marker.height = 40 self.addressView.isHidden = true return false // 이벤트 넘겨줌, -mapView:didTapMap:point 이벤트가 발생할 수 있음 } } new_marker.mapView = mapView print(latitude) print(longitude) // Do any additional setup after loading the view. } private func requestAuthorization() { //정확도 검사 locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters //앱 사용할때 권한요청 switch locationManager.authorizationStatus { case .restricted, .denied: print("restricted n denied") locationManager.requestWhenInUseAuthorization() case .authorizedWhenInUse, .authorizedAlways: print("권한있음") locationManagerDidChangeAuthorization(locationManager) default: locationManager.startUpdatingLocation() print("default") } locationManagerDidChangeAuthorization(locationManager) if(latitude_HVC == 0.0 || longitude_HVC == 0.0){ print("위치를 가져올 수 없습니다.") } } func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { if manager.authorizationStatus == .authorizedWhenInUse || manager.authorizationStatus == .authorizedAlways { if let currentLocation = locationManager.location?.coordinate{ print("coordinate") longitude_HVC = currentLocation.longitude latitude_HVC = currentLocation.latitude } } else{ print("else") } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last { latitude_HVC = location.coordinate.latitude longitude_HVC = location.coordinate.longitude } } }
[참고자료]
개발자 등록 없이 내 아이폰에 테스트 앱 설치하기
개발자 등록 없이 Xcode에서 만든 앱을 내 아이폰에 설치해보자.
sweepty.medium.com
https://plcprogrammer-dy.tistory.com/58
[iOS] 위치 권한 설정하기
안녕하세요 ! 오늘은 위치 정보가 필요할 때 위치 권한을 얻는 방법을 공부해보겠습니다 iOS 13 기준으로 설명드릴게요 공식 문서로 자세하게 찾아보겠습니다. 1. 위치 정보를 받기 전에 requestAlway
plcprogrammer-dy.tistory.com
https://2island.tistory.com/35
[swift | ios] 네이버 지도 API로 현위치 트래킹, 마커 표시 해보기
사전 세팅 - Snapkit으로 View 띄워보기 (스토리보드 없이) - Naver Maps Client Id Xcode에 추가해놓기 구현해볼 기능 - 네이버 지도를 화면에 띄워보기 - 현재위치 좌표 (위도, 경도) 구하기 - 현재위치로 카
2island.tistory.com
https://swift-it-world.tistory.com/24
Swift 현재 위치 받아오기 (위도, 경도)
CoreLocation을 이용하여 위치정보를 받아와 위도 경도를 알아낼 수 있습니다. 주석에 각 코드의 설명을 적어놓았습니다. Info.plist에 Privacy - Location When In Use Usage Description을 추가하여 Value 부분에 원
swift-it-world.tistory.com
https://october-east-sea.tistory.com/167
[네이버지도API] 해당 지역에 마커 찍기, 마커 아이콘 변경
이 포스트는 ClientID 발급 이후의 과정을 담고 있는 포스트입니다. 예제를 보러오신 분은 구분선 아래 소스를 봐주세요. 우선 네이버 클라우드 플랫폼에 가입해야합니다. 가입 절차는 아래 주소
october-east-sea.tistory.com
'ToyProject' 카테고리의 다른 글
[DB] #7 ERD Cloud 이용해서 DB 설계 및 SQL 사용하기 (0) 2023.06.21 [DB] #6 DataGrip 이용해서 CSV 파일 Import (0) 2023.06.21 [iOS] #4 Naver 지도 API 사용하기 (0) 2023.06.21 [iOS] #3 LaunchScreen - 로딩화면 만들기! (0) 2023.06.20 [iOS] #2 ColorSet 세팅 및 AppIcon 지정 (0) 2023.06.20