简体   繁体   English

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

[英]How to open maps App programmatically with coordinates in swift?

I have latitude and longitude that I want to open into my map application.我有要在 map 应用程序中打开的纬度和经度。 I tried this code from HERE .我从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)

}

This function successfully open maps but it doesn't show any pin.这个 function 成功打开地图,但它没有显示任何引脚。 Also it shows user location which I don't want.它还显示了我不想要的用户位置。 I only want a pin on the map for the provided latitude and longitude.我只想要 map 上提供的纬度和经度的引脚。

This code is working fine for me.这段代码对我来说很好用。

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)
    
}

For swift 3.0:对于 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:斯威夫特 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)

If you just want to give the user driving directions, here's the latest Swift syntax in its simplest form:如果您只想为用户提供行车路线,这里是最简单形式的最新 Swift 语法:

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

You could call class function of MKMapItem passing items there, it uses only first and last for source / destination appropriately, if you want pass more than two items.您可以调用MKMapItem类函数在MKMapItem传递项目,如果您想传递两个以上的项目,它仅适当地使用第一个和最后一个作为源/目标。

Swift 5, 4斯威夫特 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]
)

or using extension:或使用扩展名:

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

The MKMapItem approach above works great if you want granular control over the information that is displayed in Maps.如果您希望对地图中显示的信息进行精细控制,则上述MKMapItem方法非常有效。

Otherwise, the code below works great as well, :否则,下面的代码也很好用,:

// 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)!)

However, the code above does not let you to send in a custom name of the place.但是,上面的代码不允许您发送地点的自定义名称。 Instead, it will show the address.相反,它将显示地址。

The code above also lets you navigate from any source coordinate, which I don't know if you can do with the MKMapItem approach.上面的代码还可以让您从任何源坐标进行导航,我不知道您是否可以使用 MKMapItem 方法。

This works as a charm for me这对我来说是一种魅力

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)

You can use below code to show PIN on lat, long in to Apple map.您可以使用以下代码在 lat 上显示 PIN,长在 Apple 地图中。

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

If what you want is something simple without importing any framework you can just create a URL: https://maps.apple.com/?ll=\\(latitude),\\(longitude)如果您想要的只是简单而无需导入任何框架的内容,您只需创建一个 URL: https://maps.apple.com/?ll=\\(latitude),\\(longitude) : https://maps.apple.com/?ll=\\(latitude),\\(longitude) \\( https://maps.apple.com/?ll=\\(latitude),\\(longitude)

Is similar to @saniel-saidi response but this one opens just the map with location sent, not the navigation thing类似于@saniel-saidi 响应,但此响应仅打开带有已发送位置的地图,而不是导航内容

Update to the practical Daniel Saidi answer .更新实用的 Daniel Saidi答案 This example is for telling only the destination coordinates.此示例仅用于告知目的地坐标。 Maps will get as origin the user current position.地图将获得用户当前位置作为原点。

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

I know all answers are complete but here I got an answer which is easier to copy paste & also gives the user options to routing with Apple Maps, Google Map & Waze.我知道所有答案都是完整的,但在这里我得到了一个更容易复制粘贴的答案,并且还为用户提供了使用 Apple Maps、Google Map 和 Waze 进行路由的选项。

Working with Swift 5+使用Swift 5+

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

Might help someone...可能会帮助某人...

The simplest way to open the Apple Maps app and show a pin on the custom location with a custom title is that:打开 Apple Maps 应用程序并在具有自定义标题的自定义位置上显示图钉的最简单方法是:

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

Look here for more options: https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html在这里查看更多选项: https : //developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html

Swift 5 Solution: Swift 5 解决方案:

Open Apple Map OR Google Map Programmatically以编程方式打开 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)
                }
            }
        }
    

Don't forget to write this in info.plist不要忘记在 info.plist 中写这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM