Open Map Apple From My App Swift 5.1


This example For open map iPhone from project app swift 5.1, this example user input textfield for
by longitude, latitude & place name. check this full code in below.


import MapKit
import UIKit

class Day64ViewController: UIViewController {
    @IBOutlet weak var bton: UIButton!
    @IBOutlet weak var latitudeInput: UITextField!
    @IBOutlet weak var longitudeInput: UITextField!
    @IBOutlet weak var placeNameInput: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        bton.addTarget(self, action: #selector(handleViewMap(_:)), for: .touchDown)
        
    }
    
    @objc func handleViewMap(_ sender: UIButton) {
        let _lattitide = Double("\(latitudeInput.text ?? "")") ?? 0.0
        let _longitude = Double("\(longitudeInput.text ?? "")") ?? 0.0
        self.openMapForPlace(_lattitide, _longitude, placeNameInput.text ?? "")
        
    }

    func openMapForPlace(_ lat: Double, _ long: Double, _ placeName: String) {
        let latitude: CLLocationDegrees = lat
        let longitude: CLLocationDegrees = long

        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 = placeName
        mapItem.openInMaps(launchOptions: options)
    }
}

No comments: