繁体   English   中英

在按钮功能中添加两个坐标以启动mapKit并开始两点之间的导航(Swift)

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

我正在上课

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





    }

用谷歌地图添加地点标记,在地图上绘制方向并显示两点之间的距离,现在我想在startLocation: userLocation!之间启动导航startLocation: userLocation! endLocation: coordinates但是通过一些研究我看到我无法在同一视图中启动导航器,我需要打开地图应用程序,所以我决定添加MapKit和一个按钮

@IBAction func navigationStart(_ sender: Any) {


}

那么我怎么能按下地图应用程序打开的按钮,方向是userLocationcoordinates 我已经看过类似的问题,但与我的问题有点不同,因为我已经有了不同格式的分数。

您的问题有点令人困惑,但如果您想打开地图应用并显示从用户当前位置到地图上另一个点的方向,那么您不需要传递用户的位置,只需传递目的地:

斯威夫特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])

目标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}];

暂无
暂无

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

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