Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
986 views
in Technique[技术] by (71.8m points)

ios - Draw polyline using Google Maps in custom view with Swift 3

I am trying to draw route between two places using Google Maps on a custom UIView but not able to get it correctly implemented. My custom view is mapViewX. I've installed google sdk using pods which includes pod 'GoogleMaps' and pod 'GooglePlaces'. I made custom-view Class as 'GMSMapView'. my code is :

    @IBOutlet weak var mapViewX: GMSMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let path = GMSMutablePath()
    path.add(CLLocationCoordinate2D(latitude: 37.778483, longitude: -122.513960))
    path.add(CLLocationCoordinate2D(latitude: 37.706753, longitude: -122.418677))
    let polyline = GMSPolyline(path: path)
    polyline.strokeColor = .black
    polyline.strokeWidth = 10.0
    polyline.map = mapViewX

}

Please help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It works fine here. Make sure you're setting correct coordinates of GMSCameraPosition.

EDIT

To draw the route between two coordinate, use Google Maps Direction API

Something like :

    let origin = "(37.778483),(-122.513960)"
    let destination = "(37.706753),(-122.418677)"
    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=(origin)&destination=(destination)&mode=driving&key=[YOUR-API-KEY]"

    Alamofire.request(url).responseJSON { response in
        let json = JSON(data: response.data!)
        let routes = json["routes"].arrayValue

        for route in routes
        {
            let routeOverviewPolyline = route["overview_polyline"].dictionary
            let points = routeOverviewPolyline?["points"]?.stringValue
            let path = GMSPath.init(fromEncodedPath: points!)

            let polyline = GMSPolyline(path: path)
            polyline.strokeColor = .black
            polyline.strokeWidth = 10.0
            polyline.map = mapViewX

        }
    }

For more info - Directions API Developer's Guide


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...