How to open maps App programmatically with coordinates in swift?

前端 未结 9 2214
忘了有多久
忘了有多久 2020-11-30 18:40

I have latitude and longitude that I want to open into my map application. I tried this code from HERE.

    func goToMap(){

    var lat1 : NSString = self.v         


        
相关标签:
9条回答
  • 2020-11-30 19:32

    If what you want is something simple without importing any framework you can just create a URL: 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

    0 讨论(0)
  • 2020-11-30 19:38

    The MKMapItem approach above works great if you want granular control over the information that is displayed in Maps.

    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.

    0 讨论(0)
  • 2020-11-30 19:38

    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)
    
    0 讨论(0)
提交回复
热议问题