Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...