简体   繁体   中英

Add two coordinates in a button function to launch mapKit and start navigation between two points (Swift)

I'm using this class

import UIKit
import CoreLocation
import GoogleMaps
import GooglePlaces
import SwiftyJSON
import Alamofire
import MapKit

class FinalClass: UIViewController {

    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var bottomInfoView: UIView!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var distanceLabel: UILabel!



    var userLocation:CLLocationCoordinate2D?
    var places:[QPlace] = []
    var index:Int = -1

    var locationStart = CLLocation()
    var locationEnd = CLLocation()

    var mapView:GMSMapView!
    var marker:GMSMarker?






    override func loadView() {
        super.loadView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()



        guard index >= 0, places.count > 0 else {
            return


        }

        let place = places[index]
        let lat = place.location?.latitude ?? 1.310844
        let lng = place.location?.longitude ?? 103.866048

        // Google map view
        let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 12.5)
        mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)
        mapView.autoresizingMask = [.flexibleHeight, .flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin]
        self.containerView.addSubview(mapView)

        // Add gesture
        addSwipeGesture()

        didSelect(place: place)
        if userLocation != nil {
            addMarkerAtCurrentLocation(userLocation!)

        }
    }

    func addSwipeGesture() {
        let directions: [UISwipeGestureRecognizerDirection] = [.right, .left]
        for direction in directions {
            let gesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
            gesture.direction = direction
            self.bottomInfoView.addGestureRecognizer(gesture)
        }
    }

    func addMarkerAtCurrentLocation(_ userLocation: CLLocationCoordinate2D)  {
        let marker = GMSMarker()
        marker.position = userLocation
        marker.title = "Your location"
        marker.map = mapView
    }

    func didSelect(place:QPlace) {

        guard let coordinates = place.location else {
            return
        }

        // clear current marker
        marker?.map = nil

        // add marker
        marker = GMSMarker()
        marker?.position = coordinates
        marker?.title = place.name
        marker?.map = mapView
        mapView.selectedMarker = marker
        moveToMarker(marker!)

        // update bottom info panel view
        let desc = place.getDescription()
        descriptionLabel.text = desc.characters.count > 0 ? desc : "-"
        distanceLabel.text = "-"

        // update distance
        if userLocation != nil {
            let dist = distance(from: userLocation!, to: coordinates)
            distanceLabel.text = String.init(format: "Distance %.2f meters", dist)
            self.drawPath(startLocation: userLocation!, endLocation: coordinates)
        }

        title = place.name
    }

    func moveToMarker(_ marker: GMSMarker) {
        let camera = GMSCameraPosition.camera(withLatitude: marker.position.latitude,
                                              longitude: marker.position.longitude,
                                              zoom: 12.5)
        self.mapView.animate(to: camera)
    }

    // distance between two coordinates
    func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
        let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
        let to = CLLocation(latitude: to.latitude, longitude: to.longitude)

       return from.distance(from: to)

    }

    func handleSwipe(sender: UISwipeGestureRecognizer) {

        guard index >= 0, places.count > 0 else {
            return
        }

        if sender.direction == .left {
            if index < places.count - 2 {
                index += 1
                didSelect(place: places[index])
            }
        } else if sender.direction == .right {
            if index > 1 {
                index -= 1
                didSelect(place: places[index])
            }
        }
    }




    func drawPath(startLocation: CLLocationCoordinate2D, endLocation: CLLocationCoordinate2D) {

        let from = CLLocation(latitude: startLocation.latitude, longitude: startLocation.longitude)
        let to = CLLocation(latitude: endLocation.latitude, longitude: endLocation.longitude)

        let origin = "\(from.coordinate.latitude),\(from.coordinate.longitude)"
        let destination = "\(to.coordinate.latitude),\(to.coordinate.longitude)"


        let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving"

        Alamofire.request(url).responseJSON { response in

            print(response.request as Any)  // original URL request
            print(response.response as Any) // HTTP URL response
            print(response.data as Any)     // server data
            print(response.result as Any)   // result of response serialization

            let json = JSON(data: response.data!)
            let routes = json["routes"].arrayValue

            // print route using Polyline
            for route in routes
            {
                let routeOverviewPolyline = route["overview_polyline"].dictionary
                let points = routeOverviewPolyline?["points"]?.stringValue
                let path = GMSPath.init(fromEncodedPath: points!)
                let polyline = GMSPolyline.init(path: path)
                polyline.strokeWidth = 4
                polyline.strokeColor = UIColor.black
                polyline.map = self.mapView
            }

        }

    }


    @IBAction func navigationStart(_ sender: Any) {





    }

with a google maps to add place markers, draw the direction on the map and show the distance between two points, now i would like to launch the navigator between startLocation: userLocation! and endLocation: coordinates but with some research i saw that i can not launch the navigator in the same view, i need to open the maps application, so i decided to add the MapKit and a button

@IBAction func navigationStart(_ sender: Any) {


}

so how can i do that by pressing the button the map application opens with direction from userLocation to coordinates ? I already looked to similar question but is a little different to my problem, because i already have the points but in different format.

Your question is a little confusing but if you want to open the maps app and show direction from a user's current location to another point on the map then you don't need to pass the user's location, just the destination:

Swift 4:

let coordinate = CLLocationCoordinate2DMake(51.5007, -0.1246)
let placeMark = MKPlacemark(coordinate: coordinate)
let mapItem = MKMapItem(placemark: placeMark)
mapItem.name = "Big Ben"
mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])

Objective C:

CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(51.5007, -0.1246);
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate: coordinate];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:@"Big Ben"];
[mapItem openInMapsWithLaunchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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