草庐IT

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

coder 2023-09-11 原文

我正在使用这个类

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





    }

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

@IBAction func navigationStart(_ sender: Any) {


}

那么我如何通过按下 map 应用程序以从 userLocationcoordinates 的方向打开的按钮来做到这一点?我已经看过类似的问题,但与我的问题有点不同,因为我已经有了要点,但格式不同。

最佳答案

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

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

关于ios - 在按钮函数中添加两个坐标以启动 mapKit 并开始两点之间的导航(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47095622/

有关ios - 在按钮函数中添加两个坐标以启动 mapKit 并开始两点之间的导航(Swift)的更多相关文章

  1. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  2. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  3. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  4. ruby-on-rails - 启动 Rails 服务器时 ImageMagick 的警告 - 2

    最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru

  5. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  6. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  7. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  8. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  9. ruby-on-rails - `a ||= b` 和 `a = b if a.nil 之间的区别? - 2

    我正在检查一个Rails项目。在ERubyHTML模板页面上,我看到了这样几行:我不明白为什么不这样写:在这种情况下,||=和ifnil?有什么区别? 最佳答案 在这种特殊情况下没有区别,但可能是出于习惯。每当我看到nil?被使用时,它几乎总是使用不当。在Ruby中,很少有东西在逻辑上是假的,只有文字false和nil是。这意味着像if(!x.nil?)这样的代码几乎总是更好地表示为if(x)除非期望x可能是文字false。我会将其切换为||=false,因为它具有相同的结果,但这在很大程度上取决于偏好。唯一的缺点是赋值会在每次运行

  10. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

随机推荐