0

I create a UIViewController where there is a mapView and some some map-related functions (like finding a user's location or putting markers). Now i want to draw the directions from a starting point var userLocation:CLLocationCoordinate2D? to an ending point var places:[QPlace] = [] so from a marker to another

      let place = places[index]
        let lat = place.location?.latitude ?? 1.310844
        let lng = place.location?.longitude ?? 103.866048
 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!)

and as you can see the QPlace class has a variable of type CLLocationCoordinate2D

import UIKit
import CoreLocation

private let geometryKey = "geometry"
private let locationKey = "location"
private let latitudeKey = "lat"
private let longitudeKey = "lng"
private let nameKey = "name"
private let openingHoursKey = "opening_hours"
private let openNowKey = "open_now"
private let vicinityKey = "vicinity"
private let typesKey = "types"
private let photosKey = "photos"


class QPlace: NSObject  {

    var location: CLLocationCoordinate2D?
    var name: String?
    var photos: [QPhoto]?
    var vicinity: String?
    var isOpen: Bool?
    var types: [String]?

    init(placeInfo:[String: Any]) {
        // coordinates
        if let g = placeInfo[geometryKey] as? [String:Any] {
            if let l = g[locationKey] as? [String:Double] {
                if let lat = l[latitudeKey], let lng = l[longitudeKey] {
                    location = CLLocationCoordinate2D.init(latitude: lat, longitude: lng)
                }
            }
        }

        // name
        name = placeInfo[nameKey] as? String

        // opening hours
        if let oh = placeInfo[openingHoursKey] as? [String:Any] {
            if let on = oh[openNowKey] as? Bool {
                isOpen = on
            }
        }

        // vicinity
        vicinity = placeInfo[vicinityKey] as? String

        // types
        types = placeInfo[typesKey] as? [String]

        // photos
        photos = [QPhoto]()
        if let ps = placeInfo[photosKey] as? [[String:Any]] {
            for p in ps {
                photos?.append(QPhoto.init(photoInfo: p))
            }
        }
    }

    func getDescription() -> String {

        var s : [String] = []

        if let name = name {
            s.append("Name: \(name)")
        }

        if let vicinity = vicinity {
            s.append("Vicinity: \(vicinity)")
        }

        if let types = types {
            s.append("Types: \(types.joined(separator: ", "))")
        }

        if let isOpen = isOpen {
            s.append(isOpen ? "OPEN NOW" : "CLOSED NOW")
        }

        return s.joined(separator: "\n")
    }

    func heightForComment(_ font: UIFont, width: CGFloat) -> CGFloat {
        let desc = getDescription()
        let rect = NSString(string: desc).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return ceil(rect.height)
    }


}

but my function to draw the map expected to use and object of type CLLocation, this is my func

func drawPath(startLocation: CLLocation, endLocation: CLLocation)
    {
        let origin = "\(startLocation.coordinate.latitude),\(startLocation.coordinate.longitude)"
        let destination = "\(endLocation.coordinate.latitude),\(endLocation.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.red
                polyline.map = self.mapView
            }

        }
    }

so how can i do to solve this problem and instantiate an object of type CLLocation that accepts the parameters i have in QPlace and userLocation ? (I'm sorry to have put so much code but it was the only way to explain it clearly)

rmaddy
  • 314,917
  • 42
  • 532
  • 579
seran
  • 97
  • 1
  • 11
  • Is all you want to know is how to create a `CLLocation` from a `CLLocationCoordinate2D`? You don't need to post any code to ask that. – rmaddy Oct 29 '17 at 17:11
  • @rmaddy how can i do? – seran Oct 29 '17 at 17:12
  • 1
    Have you looked at the documentation for those two? Look at the possible `init` methods of `CLLocation`. Look at the values you get from `CLLocationCoordinate2D`. – rmaddy Oct 29 '17 at 17:13
  • @rmaddy if you know how to solve my situation with the code i showed well, otherwise sorry but these comments are not useful, if i was able to look at the documentation and do it myself, I would not ask this question – seran Oct 29 '17 at 17:20
  • @rmaddy you marked the question as duplicate, wow, you're really helpful, great job! – seran Oct 29 '17 at 17:52
  • Are you being sarcastic? Did you look at the answer to the duplicate? Does is not answer your question of how to create a `CLLocation` from `CLLocationCoordinate2D`? – rmaddy Oct 29 '17 at 17:55
  • @rmaddy if it was so easy, i would not ask the question, i'm a beginner and that answer is a generic way of solving the problem, i wanted to see how I had to do in my specific case – seran Oct 29 '17 at 17:59
  • Then you need to clarify your question. First, you posted way too much code. Second, if your question isn't a simple matter of converting from `CLLocationCoordinate2D` to `CLLocation`, then you need to clarify what your question is. My very first comment asked you to clarify this and your first comment implied that is all you needed. – rmaddy Oct 29 '17 at 18:01
  • @rmaddy you see my code, i only want to make the function to draw the direction on the map work, from the user location to the place – seran Oct 29 '17 at 18:06

0 Answers0