【问题标题】:Swift iOS google Map, path to coordinateSwift iOS google Map,坐标路径
【发布时间】:2015-05-01 06:49:41
【问题描述】:

我正在尝试在我的应用程序中创建一个函数,将用户引导至我创建的标记。 这是我正在使用的代码,效果很好,它可以获取用户当前位置并将其显示在地图上。但是我怎样才能获得到标记的路线呢?

任何遮阳篷都会有所帮助

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()
        }
    }
}

【问题讨论】:

    标签: swift google-maps-sdk-ios directions


    【解决方案1】:

    所以我最近刚刚解决了这个问题,这是我使用最新版本的 Alamofire (4.3) 实现的 Swift 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 中缺失
    【解决方案2】:

    免责声明: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 是什么?
    • 它只包含键值对..关于不同键中路线的信息..但是我们主要关心的是折线点....
    • 经过大约 1 天的编码后,它对我有用。那是我的坏技能。感谢您的代码:)
    • @Anish웃.. 这对我有帮助。一个疑问我从服务器获取纬度和经度如何快速定位标记
    • @Anish웃.. 我已经做了一些研究。但是在跟踪用户时,它设置不正确。
    【解决方案3】:

    与 Apple 的 MapKit 不同,适用于 iOS 的 Google Maps SDK 本身不包含执行路线计算的方法。

    相反,您需要使用 Google Directions API:https://developers.google.com/maps/documentation/directions/。它是一个仅支持 HTTP 的 API,Google 至今未提供任何 SDK,但您可以轻松地自己编写自己的包装器,或者选择 Github 上提供的众多选项之一:

    【讨论】:

    • 感谢您的帮助,我会调查此事!如果我要使用此功能,您是否更愿意使用 iOS 地图?
    • 我一直在使用这两种方法,根据我自己的经验,至少在欧洲,谷歌地图通常会提供更好的结果。但是,MapKit 更易于使用,因为它与 iOS SDK 紧密集成,并且可以立即使用。
    【解决方案4】:

    非常简单 如果您在您的 iOS 项目中添加了 Google 地图 SDK,并且如果您想在两个不同方向之间实现获取 google 地图方向线,我将使用 swift 2.3 以简单的方式理解为演示代码,请尝试、修改并使用它。!! !

    注意:不要忘记更改您想要的 lat long 和 API 密钥(您可以在 Google API Manager 凭据部分使用无限制的 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
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多