如何以 swift 中的坐标以编程方式打开地图应用程序?

How to open maps App programmatically with coordinates in swift?

我有要在我的地图应用程序中打开的纬度和经度。我从 HERE.

尝试了这段代码
    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)
    }
}

Swift 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])

这对我来说很有魅力

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)

如果您希望精细控制地图中显示的信息,上述 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 方法。

您可以调用 MKMapItem 的 class 函数在那里传递项目,如果您想要传递两个以上的项目,它只适当地使用 first 和 last 作为源/目标。

Swift 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]
)

您可以使用以下代码在 Apple 地图的经纬度上显示 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 的回复,但这个回复只打开发送了位置的地图,而不是导航内容

我知道所有答案都是完整的,但在这里我得到了一个更容易复制粘贴的答案,还为用户提供了使用 Apple Maps、Google Map & Waze 进行路线选择的选项。

Swift 合作 5+

可能会帮助某人...

实用丹尼尔赛迪更新。此示例仅用于告知目的地坐标。地图将以用户当前位置为原点。

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

打开 Apple 地图应用程序并在自定义位置上显示带有自定义标题的图钉的最简单方法是:

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

Swift 5 解:

打开 APPLE 地图或 GOOGLE 以编程方式打开地图

  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>