swift

SwiftUI kakao map, Naver map, Tmap, apple map 길찾기 구현하기

호리둥절 2023. 5. 22. 14:27

Info.plist 에 scheme 등록하기

URL Scheme(또는 URI Scheme)은 특정 애플리케이션을 실행하거나 특정 동작을 수행하기 위해 사용되는 URL의 형식입니다. URL Scheme은 애플리케이션 간의 통신이나 앱 내부의 기능 호출에 사용될 수 있습니다.

 

예를 들어, iOS에서는UIApplication.shared.openURL(_:) 메서드를 사용하여 지정된 URL Scheme으로 애플리케이션을 실행할 수 있습니다.

 

kakaomap:// 으로 호출하면 카카오 맵으로 이동하게 됩니다.

이렇게 ios 앱에선 URL Scheme 를 통해 다른 앱으로 이동할 수 있습니다.

 

1 . 직접 Info.plist에 scheme등록하기

	<key>LSApplicationQueriesSchemes</key>
	<array>
		<string>tmap</string>
		<string>nmap</string>
		<string>kakaomap</string> 
	</array>

 OR 

2. Targets에서 등록해주기

project > targets > Info > custom IOS target properties

 둘중 편하신 방법으로 진행해 주시면 되겠습니다.

 


길찾기 구현하기

1. kakaoMap 길찾기 구현

func KaKaoMap(lat: Double, lng: Double) {
  	// URL Scheme을 사용하여 kakaomap 앱 열고 경로 생성합니다
    guard let url = URL(string: "kakaomap://route?ep=\(lat),\(lng)&by=CAR") else { return }
    
    // Kakaomap 앱의 App Store URL 생성
    guard let appStoreUrl = URL(string: "itms-apps://itunes.apple.com/app/id304608425") else { return }
    
    let urlString = "kakaomap://open"
    
    // Kakaomap 앱이 설치되어 있는지 확인하고 URL 열기
    if let appUrl = URL(string: urlString) {
        if UIApplication.shared.canOpenURL(appUrl) {
            UIApplication.shared.open(url)
        } else {
            // Kakaomap 앱이 설치되어 있지 않은 경우 App Store URL 열기
            UIApplication.shared.open(appStoreUrl)
        }
    }
}
  • ep 매개변수: 도착지의 위도와 경도를 설정합니다. \(lat)과 \(lng)는 주어진 위도와 경도 값을 문자열로 대체하는 부분입니다.
  • by 매개변수: 경로 계산 방법을 설정합니다. CAR는 자동차를 이용한 경로를 의미합니다.

따라서, 위의 URL을 사용하면 Kakaomap 앱이 열리고 도착지를 설정한 경로가 표시됩니다.

 

 

[ ※ 참고 ]

https://apis.map.kakao.com/ios/guide/#urlscheme

 

 

 

2. naverMap 길찾기 구현

    func NaverMap(lat: Double, lng: Double) {
        // URL Scheme을 사용하여 네이버맵 앱을 열고 자동차 경로를 생성합니다.
        guard let url = URL(string: "nmap://route/car?dlat=\(lat)&dlng=\(lng)&appname=kr.co.kepco.ElectricCar") else { return }
        // 앱 스토어 URL을 설정합니다.
        guard let appStoreURL = URL(string: "http://itunes.apple.com/app/id311867728?mt=8") else { return }

        if UIApplication.shared.canOpenURL(url) {
            // 네이버맵 앱이 설치되어 있는 경우 앱을 엽니다.
            UIApplication.shared.open(url)
        } else {
            // 네이버맵 앱이 설치되어 있지 않은 경우 앱 스토어로 이동합니다.
            UIApplication.shared.open(appStoreURL)
        }
    }
  • dlat=\(lat): 목적지의 위도 정보를 나타냅니다. lat 변수의 값으로 대체됩니다.
  • dlng=\(lng): 목적지의 경도 정보를 나타냅니다. lng 변수의 값으로 대체됩니다.
  • appname=com.example.myApp: 앱을 호출하는데 사용되는 앱 식별자를 나타냅니다. 이 식별자는 필요에 따라 앱의 번들 ID나 고유한 식별자로 대체될 수 있습니다.

이 URL Scheme을 사용하여 앱이 설치되어 있는 경우 네이버맵 앱을 열고, 자동차 경로를 생성합니다. 설치되어 있지 않은 경우에는 앱 스토어로 이동하여 네이버맵 앱을 다운로드할 수 있도록 합니다.

 

 

[ ※ 참고 ]

https://guide.ncloud-docs.com/docs/naveropenapiv3-maps-url-scheme-url-scheme

 

지도앱 연동 URL Scheme

 

guide.ncloud-docs.com

 

 

 

3. tMap 길찾기 구현

  func TMap(lat:Double, lng:Double){
        // URL Scheme을 사용하여 티맵 앱을 열고 자동차 경로를 생성합니다.
        let urlStr = "tmap://route?rGoName=목적지&rGoX=\(lng)&rGoY=\(lat)"
        
        // URL 문자열을 인코딩하여 올바른 형식으로 변환합니다.
        guard let encodedStr = urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return }
        
        // 인코딩된 URL 문자열을 URL 객체로 변환합니다.
        guard let url = URL(string: encodedStr) else { return }
        
        // TMap 앱이 설치되어 있는지 확인합니다.
        if UIApplication.shared.canOpenURL(url) {
            // TMap 앱을 엽니다.
            UIApplication.shared.open(url)
        } else {
            // TMap 앱이 설치되어 있지 않은 경우 앱 스토어로 이동합니다.
            guard let appStoreURL = URL(string: "http://itunes.apple.com/app/id431589174") else { return }
            UIApplication.shared.open(appStoreURL)
        }
    }
  • rGoName 매개변수는 목적지의 이름 또는 주소를 나타냅니다. "목적지"는 해당 값으로 대체됩니다.
  • rGoX와 rGoY 매개변수는 목적지의 경도와 위도를 나타냅니다. lng와 lat 변수가 각각 해당 값으로 대체됩니다.

URL Scheme을 사용하여 앱을 호출하는 경우, 해당 앱이 설치되어 있는지 먼저 확인하고, 설치되어 있다면 TMap 앱을 엽니다. rGoName 매개변수에는 목적지의 이름 또는 주소를 설정하고, rGoX와 rGoY 매개변수에는 목적지의 경도와 위도를 설정합니다. 이를 통해 TMap 앱이 열리고 지정된 목적지로의 경로가 표시됩니다.

 

[ ※ 참고 ]

https://tmapapi.sktelecom.com/main.html#iosv2VSM/sample/iosSample.sample43

 

Guide | T MAP API

 

tmapapi.sktelecom.com

 

 

4. apple 길찾기 구현

func AppleMap(addr: String) {
        let urlStr = "maps://?daddr=\(addr)&dirfgl=d"
        
        // 한글 인코딩
        guard let encodedStr = urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return }
        guard let url = URL(string: encodedStr) else { return }
        
        // 애플지도 앱스토어 url
        guard let appStoreUrl = URL(string: "itms-apps://itunes.apple.com/app/id915056765") else { return }
        
        // 애플지도 앱이 있다면,
        if UIApplication.shared.canOpenURL(url) {
            // 애플 길찾기 open
            UIApplication.shared.open(url)
        } else { // 애플 지도 앱이 없다면,
            // 애플지도 설치 앱스토어로 이동
            UIApplication.shared.open(appStoreUrl)
        }
    }
  • daddr 매개변수는 목적지의 주소를 나타냅니다. addr 변수가 해당 값으로 대체됩니다.
  • dirflg 매개변수는 경로 타입을 지정합니다. d는 운전 모드를 의미합니다.

애플지도의 특이점은 다른것들은 위치값으로 목적지를 찾지만 애플지도는 주소값으로 목적지를 찾습니다

 

URL Scheme을 사용하여 앱을 호출하는 경우, 해당 앱이 설치되어 있는지 먼저 확인하고, 설치되어 있다면 Apple Maps 앱을 엽니다. daddr 매개변수의 값을 설정하여 목적지 주소를 지정하고, dirflg 매개변수의 값을 d로 설정하여 운전 경로를 표시합니다.

 

[ ※ 참고 ]

https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html

 

Map Links

Map Links The maps URL scheme is used to show geographical locations and to generate driving directions between two points. If your app includes address or location information, you can use map links to open that information in the Maps app in iOS or macOS

developer.apple.com

 

사용하는 부분 코드

   VStack(alignment: .leading,spacing:0){
                        Text("경로안내")
                            .font(.MediumL)
                            .foregroundColor(Color(hex:"#010D37"))
                            .padding(.vertical,10)
                        HStack(spacing:15){
                            Button{
                                mapService.KaKaoMap(lat: locationViewModel.coord.1, lng: locationViewModel.coord.0)
                            }label:{
                                VStack{
                                    Image("routeGuid1")
                                    Text("카카오")
                                        .foregroundColor(Color(hex:"#B8B8B8"))
                                        .font(.RegularS)
                                }
                            }
                            
                            Button{
                                mapService.TMap(lat: locationViewModel.coord.1, lng: locationViewModel.coord.0)
                            }label:{
                                VStack{
                                    Image("routeGuid2")
                                    Text("티맵")
                                        .foregroundColor(Color(hex:"#B8B8B8"))
                                        .font(.RegularS)
                                }
                            }
                            Button{
                                mapService.NaverMap(lat: locationViewModel.coord.1, lng: locationViewModel.coord.0)
                            }label:{
                                VStack{
                                    Image("routeGuid3")
                                    Text("네이버")
                                        .foregroundColor(Color(hex:"#B8B8B8"))
                                        .font(.RegularS)
                                }
                            }
                            Button{
                                mapService.AppleMap(addr: viewModel.chargingStationDetail[0].addr ?? "")
                            }label:{
                                VStack{
                                    Text("에플")
                                        .foregroundColor(Color(hex:"#B8B8B8"))
                                        .font(.RegularS)
                                }
                            }
                        }
                    }

mapservice struct에서 각각 해당하는 함수를 호출하여 사용하였다.