Swift iOS 谷歌地图,路径到坐标

5
我正在尝试在我的应用程序中创建一个函数,该函数将引导用户到我创建的标记。这是我使用的代码,它运行良好,它获取用户当前位置并在地图上显示它。但是如何获得指向标记的方向?任何答案都将有所帮助。
class Karta: UIViewController, CLLocationManagerDelegate {
    @IBOutlet var mapView: GMSMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        //allow app to track user
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()

        //set out a marker on the map
        var marker = GMSMarker()
        marker.position = CLLocationCoordinate2DMake(56.675907, 12.858798)
        marker.appearAnimation = kGMSMarkerAnimationPop
        marker.icon = UIImage(named: "flag_icon")
        marker.map = mapView
     }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "Types Segue" {
            let navigationController = segue.destinationViewController as UINavigationController
        }
    }

    func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

        //If map is being used
        if status == .AuthorizedWhenInUse {
            var myLocation = mapView
            locationManager.startUpdatingLocation()
            mapView.myLocationEnabled = true
            mapView.settings.myLocationButton = true
        }
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if let location = locations.first as? CLLocation {
            mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
          locationManager.stopUpdatingLocation()
        }
    }
}
4个回答

18

我最近刚刚解决了这个问题,以下是我的 Swift 3 实现,使用了最新版本的 Alamofire(4.3)

 func fetchMapData() { 

    let directionURL = "https://maps.googleapis.com/maps/api/directions/json?" +
        "origin=\(originAddressLat),\(originAddressLng)&destination=\(destinationAddressLat),\(destinationAddressLong)&" +
    "key=YOUROWNSERVERKEY"



    Alamofire.request(directionURL).responseJSON
        { response in

            if let JSON = response.result.value {

                let mapResponse: [String: AnyObject] = JSON as! [String : AnyObject]

                let routesArray = (mapResponse["routes"] as? Array) ?? []

                let routes = (routesArray.first as? Dictionary<String, AnyObject>) ?? [:]

                let overviewPolyline = (routes["overview_polyline"] as? Dictionary<String,AnyObject>) ?? [:]
                let polypoints = (overviewPolyline["points"] as? String) ?? ""
                let line  = polypoints

                self.addPolyLine(encodedString: line)
        }
    }

}

func addPolyLine(encodedString: String) {

    let path = GMSMutablePath(fromEncodedPath: encodedString)
    let polyline = GMSPolyline(path: path)
    polyline.strokeWidth = 5
    polyline.strokeColor = .blue
    polyline.map = whateverYourMapViewObjectIsCalled

}

URL中缺少"&"符号,应该在origin之前添加。 - Avinash shirsath

8

免责声明:Swift 2

 func addOverlayToMapView(){

        let directionURL = "https://maps.googleapis.com/maps/api/directions/json?origin=\(srcLocation.coordinate.latitude),\(srcLocation.coordinate.longitude)&destination=\(destLocation.coordinate.latitude),\(destLocation.coordinate.longitude)&key=Your Server Key"

        Alamofire.request(.GET, directionURL, parameters: nil).responseJSON { response in

            switch response.result {

            case .Success(let data):

                let json = JSON(data)
                print(json)

                let errornum = json["error"]


                if (errornum == true){



                }else{
                    let routes = json["routes"].array

                    if routes != nil{

                        let overViewPolyLine = routes![0]["overview_polyline"]["points"].string
                        print(overViewPolyLine)
                        if overViewPolyLine != nil{

                         self.addPolyLineWithEncodedStringInMap(overViewPolyLine!)

                        }

                    }


                }

            case .Failure(let error):

                print("Request failed with error: \(error)")

            }
        }

    }

使用这些点,我们现在可以使用fromEncodedPath从两个点创建路径。
  func addPolyLineWithEncodedStringInMap(encodedString: String) {

        let path = GMSMutablePath(fromEncodedPath: encodedString)
        let polyLine = GMSPolyline(path: path)
        polyLine.strokeWidth = 5
        polyLine.strokeColor = UIColor.yellowColor()
        polyLine.map = mapView

    }

抱歉,let json = JSON(data) 中的 JSON 是什么? - Shinichi
1
它只包含键值对,其中包含有关不同键的路线信息。然而,我们主要关注折线点。 - LC 웃
经过约一天的编码,代码现在对我起作用了。这是我的问题技能。感谢你的代码 :) - Shinichi
@Anish웃,我已经做了一些研究。但是在跟踪用户时,它没有设置正确。 - Uma Madhavi
请提出一个不同的问题。要进行跟踪,您需要使用位置管理器获取用户位置并在地图上绘制,清除先前的位置标记。或者使用默认的showUserLocation,它将根据用户位置自动更新地图,无需使用LocationManager。 - LC 웃
显示剩余2条评论

5
与 Apple 的 MapKit 不同,Google Maps SDK for iOS 没有本地包含执行路线计算的方法。相反,您需要使用 Google Directions API: https://developers.google.com/maps/documentation/directions/。它是一个仅限 HTTP 的 API,截至今天,Google 没有提供任何 SDK,但您可以轻松编写自己的包装器,或选择 Github 上可用的众多选项:https://github.com/sudeepjaiswal/GoogleDirectionshttps://github.com/sebk/GoogleDirectionshttps://github.com/iamamused/iOS-DirectionKithttps://github.com/marciniwanicki/OCGoogleDirectionsAPI 和许多其他选项...

谢谢你的帮助,我会研究一下!如果我想使用这个功能,你更喜欢使用iOS地图吗? - Dolleno
我已经同时使用过这两个,从我的个人经验来看,Google Maps通常会给出更好的结果,至少在欧洲地区是如此。然而,MapKit更易于使用,因为它与iOS SDK紧密集成,并且可以立即使用。 - Romain

2
非常简单 如果您在iOS项目中添加了Google地图SDK,并且想要实现获取两个不同方向之间的谷歌地图方向线,我已经用简单的方式制作了演示代码,使用swift 2.3易于理解,请尝试修改并使用它!
注意:请不要忘记更改您想要的纬度和经度以及API密钥(您可能在Google API管理凭据部分中使用无限制的API密钥)。
 func callWebService(){

        let url = NSURL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(18.5235),\(73.7184)&destination=\(18.7603),\(73.8630)&key=AIzaSyDxSgGQX6jrn4iq6dyIWAKEOTneZ3Z8PtU")
        let request = NSURLRequest(URL: url!)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)

        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            // notice that I can omit the types of data, response and error
            do{
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {

                    //print(jsonResult)

                    let routes = jsonResult.valueForKey("routes")
                    //print(routes)

                    let overViewPolyLine = routes![0]["overview_polyline"]!!["points"] as! String
                    print(overViewPolyLine)

                    if overViewPolyLine != ""{

                        //Call on Main Thread
                        dispatch_async(dispatch_get_main_queue()) {

                            self.addPolyLineWithEncodedStringInMap(overViewPolyLine)
                        }


                    }

                }
            }
            catch{

                print("Somthing wrong")
            }
        });

        // do whatever you need with the task e.g. run
        task.resume()
    }

    func addPolyLineWithEncodedStringInMap(encodedString: String) {


        let camera = GMSCameraPosition.cameraWithLatitude(18.5204, longitude: 73.8567, zoom: 10.0)
        let mapView = GMSMapView.mapWithFrame(CGRect.zero, camera: camera)
        mapView.myLocationEnabled = true

        let path = GMSMutablePath(fromEncodedPath: encodedString)
        let polyLine = GMSPolyline(path: path)
        polyLine.strokeWidth = 5
        polyLine.strokeColor = UIColor.yellowColor()
        polyLine.map = mapView

        let smarker = GMSMarker()
        smarker.position = CLLocationCoordinate2D(latitude: 18.5235, longitude: 73.7184)
        smarker.title = "Lavale"
        smarker.snippet = "Maharshtra"
        smarker.map = mapView

        let dmarker = GMSMarker()
        dmarker.position = CLLocationCoordinate2D(latitude: 18.7603, longitude: 73.8630)
        dmarker.title = "Chakan"
        dmarker.snippet = "Maharshtra"
        dmarker.map = mapView

        view = mapView

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接