programing

신속하게 좌표로 프로그래밍된 지도 앱을 여는 방법은?

css3 2023. 9. 27. 18:06

신속하게 좌표로 프로그래밍된 지도 앱을 여는 방법은?

지도 응용프로그램에 열고 싶은 위도와 경도가 있습니다.이 코드는 여기서 해봤습니다.

    func goToMap(){

    var lat1 : NSString = self.venueLat
    var lng1 : NSString = self.venueLng

    var latitude:CLLocationDegrees =  lat1.doubleValue
    var longitude:CLLocationDegrees =  lng1.doubleValue

    var coordinate = CLLocationCoordinate2DMake(latitude, longitude)

    var placemark : MKPlacemark = MKPlacemark(coordinate: coordinate, addressDictionary:nil)

    var mapItem:MKMapItem = MKMapItem(placemark: placemark)

    mapItem.name = "Target location"

    let launchOptions:NSDictionary = NSDictionary(object: MKLaunchOptionsDirectionsModeDriving, forKey: MKLaunchOptionsDirectionsModeKey)

    var currentLocationMapItem:MKMapItem = MKMapItem.mapItemForCurrentLocation()

    MKMapItem.openMapsWithItems([currentLocationMapItem, mapItem], launchOptions: launchOptions)

}

이 기능은 성공적으로 지도를 열었지만 핀이 표시되지 않습니다.또한 내가 원하지 않는 사용자 위치를 보여줍니다.저는 제공된 위도와 경도에 대한 지도의 핀만 원합니다.

이 코드는 제게 잘 작동합니다.

func openMapForPlace() {
    
    let lat1 : NSString = self.venueLat
    let lng1 : NSString = self.venueLng
    
    let latitude:CLLocationDegrees =  lat1.doubleValue
    let longitude:CLLocationDegrees =  lng1.doubleValue
    
    let regionDistance:CLLocationDistance = 10000
    let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
    let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
    let options = [
        MKLaunchOptionsMapCenterKey: NSValue(MKCoordinate: regionSpan.center),
        MKLaunchOptionsMapSpanKey: NSValue(MKCoordinateSpan: regionSpan.span)
    ]
    let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = "\(self.venueName)"
    mapItem.openInMapsWithLaunchOptions(options)
    
}

swift 3.0의 경우:

import UIKit
import MapKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        openMapForPlace()
    }
    
    func openMapForPlace() {
        
        let latitude: CLLocationDegrees = 37.2
        let longitude: CLLocationDegrees = 22.9
        
        let regionDistance:CLLocationDistance = 10000
        let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
        let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
        let options = [
            MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
            MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
        ]
        let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = "Place Name"
        mapItem.openInMaps(launchOptions: options)
    }
}

스위프트 5:

let latitude: CLLocationDegrees = Double(K.latitude)!
let longitude: CLLocationDegrees = Double(K.longitude)!
let regionDistance:CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionSpan = MKCoordinateRegion(center: coordinates, latitudinalMeters: regionDistance, longitudinalMeters: regionDistance)
let options = [
    MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
    MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = K.companyName
mapItem.openInMaps(launchOptions: options)

사용자에게 운전 방향을 알려주고 싶다면, 가장 간단한 형태의 최신 Swift 구문을 소개합니다.

let coordinate = CLLocationCoordinate2DMake(theLatitude,theLongitude)
let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary:nil))
mapItem.name = "Target location"
mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving])

당신은 클래스 함수를 부를 수 있습니다.MKMapItem여기에 항목을 전달하면 소스/대상에 대해 처음과 마지막 항목만 적절하게 사용합니다. 만약 두 개 이상의 항목을 전달하고 싶다면요.

스위프트 5,4

let source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lat, longitude: lng)))
source.name = "Source"
        
let destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lat, longitude: lng)))
destination.name = "Destination"
        
MKMapItem.openMaps(
  with: [source, destination], 
  launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
)

확장명 사용:

extension MKMapItem {
  convenience init(coordinate: CLLocationCoordinate2D, name: String) {
    self.init(placemark: .init(coordinate: coordinate))
    self.name = name
  }
}

let source = MKMapItem(coordinate: .init(latitude: lat, longitude: lng), name: "Source")
let destination = MKMapItem(coordinate: .init(latitude: lat, longitude: lng), name: "Destination")

MKMapItem.openMaps(
  with: [source, destination], 
  launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
)

MKMapItem위의 접근 방법은 지도에 표시된 정보를 세부적으로 제어하고 싶을 때 효과적입니다.

그렇지 않으면 아래의 코드도 잘 작동합니다.

// Open and show coordinate
let url = "http://maps.apple.com/maps?saddr=\(coord.latitude),\(coord.longitude)"
UIApplication.shared.openURL(URL(string:url)!)

// Navigate from one coordinate to another
let url = "http://maps.apple.com/maps?saddr=\(from.latitude),\(from.longitude)&daddr=\(to.latitude),\(to.longitude)"
UIApplication.shared.openURL(URL(string:url)!)

그러나 위 코드에서는 사용자 지정 장소 이름을 보낼 수 없습니다.대신, 주소가 표시될 것입니다.

위의 코드를 사용하면 어떤 소스 좌표에서도 탐색할 수 있는데, MKMapItem 접근법으로도 가능한지 모르겠습니다.

이것은 나에게 매력으로 작용합니다.

let coordinate = CLLocationCoordinate2DMake(theLatitude, theLongitude)
let region = MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(0.01, 0.02))
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
let options = [
    MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: region.center),
    MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: region.span)]
mapItem.name = theLocationName
mapItem.openInMaps(launchOptions: options)

아래 코드를 사용하여 애플 맵에 긴 lat에 PIN을 표시할 수 있습니다.

let coordinates = CLLocationCoordinate2DMake(-37.848854,144.990295)

let regionSpan =   MKCoordinateRegionMakeWithDistance(coordinates, 1000, 1000)

let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)

let mapItem = MKMapItem(placemark: placemark)

mapItem.name = “Desired place”

mapItem.openInMaps(launchOptions:[
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center)
] as [String : Any])

원하는 것이 프레임워크를 가져오지 않고 간단한 것이라면 URL을 만들 수 있습니다.https://maps.apple.com/?ll=\(latitude),\(longitude)

@saniel-saidi 응답과 비슷하지만 이것은 내비게이션이 아닌 위치가 전송된 지도만 엽니다.

Daniel Saidi의 실제 답변을(를)이 예는 목적지 좌표만 알려주기 위한 것입니다.지도는 사용자의 현재 위치를 원점으로 가져옵니다.

let url = URL(string: "http://maps.apple.com/maps?saddr=&daddr=\(lat),\(lon)")
UIApplication.shared.open(url!)

모든 답변이 완료되었다는 것을 알고 있지만, 여기에 복사하기 더 쉽고 애플 지도, 구글 맵 & 웨즈로 라우팅할 수 있는 옵션을 제공하는 답변이 있습니다.

Swift 5+와의 협력

https://stackoverflow.com/a/60930491/6449292

누군가를 도와줄 수도...

Swift 5 솔루션:

프로그래밍 방식으로 Apple Map 또는 Google Map 열기

  let actionSheet = UIAlertController(title: "Open Location", message: "Choose an app to open direction", preferredStyle: .actionSheet)
                actionSheet.addAction(UIAlertAction(title: "Google Maps", style: .default, handler: { _ in
                    // Pass the coordinate inside this URL
                    self.openGoogleMap()
                }))
                actionSheet.addAction(UIAlertAction(title: "Apple Maps", style: .default, handler: { _ in
                    // Pass the coordinate that you want here
                    self.openAppleMap()
                }))
                actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
                self.present(actionSheet, animated: true, completion: nil)

//Function defination here


func openAppleMap(){
        guard let lat = bookingData.gpsLatitude, let latDouble =  Double(lat) else {return }
        guard let long = bookingData.gpsLongitude, let longDouble =  Double(long) else {return }
        
        let coordinate = CLLocationCoordinate2DMake(latDouble,longDouble)
                    let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate, addressDictionary: nil))
                    mapItem.name = "Destination"
                    mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
    }
    


func openGoogleMap() {
            guard let lat = bookingData.gpsLatitude, let latDouble =  Double(lat) else {return }
            guard let long = bookingData.gpsLongitude, let longDouble =  Double(long) else {return }
            if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {  //if phone has an app
                
                if let url = URL(string: "comgooglemaps-x-callback://?saddr=&daddr=\(latDouble),\(longDouble)&directionsmode=driving") {
                    UIApplication.shared.open(url, options: [:])
                }}
            else {
                //Open in browser
                if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(latDouble),\(longDouble)&directionsmode=driving") {
                    UIApplication.shared.open(urlDestination)
                }
            }
        }
    

이 내용을 info.plist에 적는 것을 잊지 마세요.

<key>LSApplicationQueriesSchemes</key>
    <array>
    <string>comgooglemaps</string>
    <string>comgooglemaps-x-callback</string>
    </array>

Apple Maps 앱을 열고 사용자 지정 제목으로 사용자 지정 위치에 핀을 표시하는 가장 간단한 방법은 다음과 같습니다.

let url = URL(string: "maps://?q=Title&ll=\(latitude),\(longitude)")!
if UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url)
}

자세한 옵션은 여기를 참조하십시오. https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html

언급URL : https://stackoverflow.com/questions/28604429/how-to-open-maps-app-programmatically-with-coordinates-in-swift