마커가 포함된 Google 지도를 추가해보겠습니다.

1. iOS용 Maps SDK 설치하기
- Xcode 버전 13.0 이상
- cocoapods이 설치되어 있어야 합니다.
podfile에 추가하기
pod 'GoogleMaps'
추가 후 pod install로 프로젝트를 꼭 재부팅시켜주세요!
2. API 키 가져오기 및 필요한 API 사용 설정
2-1. 애플리케이션에 API 키 추가
API 키를 발급받기 위에서는 아래 출처에서 회원 가입을 꼭 해야합니다. 결제용으로 핸드폰 정보도 수집하길 래 의아했는데 과도한 Api 요청이 있을 때는 비용이 청구되더라구요.
발급받은 key는 노출되지 않도록 주의해주세요!
특히 코드에 키 작성 후 github에 올리시면 안됩니다😂
https://developers.google.com/maps
Google Maps Platform | Google Developers
Google Maps Platform 설명
developers.google.com
AppDelegate.swift
import GoogleMaps
# application(_:didFinishLaunchingWithOptions:) 메서드에 키 추가하기
GMSServices.provideAPIKey("YOUR_API_KEY")
3. mapView 추가하기
* Storyboard에서 추가하기
storyboard에서는 지도가 들어가고자 하는 view 위치를 잡고 아래와 같이 설정해줍니다.
저도 처음에는 storyboard로 map을 설정했는데 위치를 적용하는 게 어렵더라구요. 코드로 적용하는 게 더 쉬웠습니다.

* 코드로 추가하기
저는 storyboard에서 map을 적용할 부분을 view로 잡고 아울렛으로 연결하고 mapView를 만들어 적용해줬습니다.
override func viewDidLoad() {
super.viewDidLoad()
let camera = GMSCameraPosition.camera(withLatitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude, zoom: 15.0) //zoom이 클수록 지도가 더 상세함.
let mapView = GMSMapView.map(withFrame: self.googleMapView.frame, camera: camera)
googleMapView = mapView
self.view.addSubview(googleMapView)
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
}

4. 사용자 위치 가져오기
위치 정보를 물어보는
HomeViewController에서 받아오기 때문에 화면전환이 될 때 사용자 위치 정보를 받아오도록 설정해줬습니다.
HomeViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
//사용자 위치
locationManager.delegate = self
//사용자가 위치 서비스 사용을 승인했는지 확인
if CLLocationManager.locationServicesEnabled() {
locationManager.requestLocation()
} else {
locationManager.requestWhenInUseAuthorization()
}
extension HomeViewController: CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
//사용자가 선택한 권한에 따라 로직이 실행되도록 한다.
guard manager.authorizationStatus == .authorizedWhenInUse else {
return
}
locationManager.requestLocation()
}
//사용자 위치 정보 얻기
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else { return }
userLocation = location
}
//오류가 발생했을 때 처리하는 로직을 작성해주어야 한다. 그렇지 않으면 아래와 같은 에러를 볼 수 있음.
// 앱에서 오류가 발생하면 콘솔에 출력되므로 오류를 처리하고 앱이 충돌하지 않도록 할 수 있다.
//Delegate must respond to locationManager:didFailWithError:'
//terminating with uncaught exception of type NSException
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
5. 위치 확인 권한 요청
info.plist에서 권한 설정하기
NSLocationWhenInUseUsageDescription을 키로 설정하고 value에 위치 권한 요청 시 사용 할 문자열을 입력해줍니다.
접근을 허용하면, 현재 위치를 활용하여 주변의 가까운 식당을 편하게 찾을 수 있어요.

출처
Google Maps iOS SDK Tutorial: Getting Started
Google Maps iOS SDK Tutorial: Getting Started
In this tutorial, you’ll learn how to use the Google Maps iOS SDK to make an app that searches for nearby places to eat, drink or shop for groceries.
www.kodeco.com
'개발 > iOS' 카테고리의 다른 글
[iOS] 웹뷰를 활용해 HTML 콘텐츠 화면에 출력하기 (0) | 2023.01.26 |
---|---|
[iOS][Swift] 세자리 콤마 넣기 (0) | 2023.01.25 |
[iOS] google map marker custom (구글맵 마커 커스텀하기) (0) | 2023.01.20 |
iOS 스토리보드(Storyboard) components 정리하기 (0) | 2023.01.19 |
[iOS] 카카오 소셜 간편 로그인( kakao login) API 연동 (0) | 2023.01.19 |