使用Swift3在GMSMapView上的两个或多个标记之间绘制折线

时间:2017-07-16 09:59:19

标签: google-maps swift3 google-maps-markers google-polyline gmsmapview

我尝试在GMSMapView上的标记之间实现绘制polyLines的不同解决方案,但是无效。你有其他解决方案,或者你知道我的代码中有什么问题吗?

    override func viewDidLoad() {
    super.viewDidLoad()
    let path = GMSMutablePath()
    _data = _modelDelivery.getGarageFromDeliver(refDelivery: _delivery._ref)
    let camera = GMSCameraPosition.camera(withLatitude: 48.853183, longitude: 2.369144, zoom: 13.0)
    self._mapView.camera = camera

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: 48.8531827, longitude: 2.3691443000000163)
    path.add(marker.position)
    marker.title = "Ma position"
    marker.icon = GMSMarker.markerImage(with: UIColor.blue)
    marker.map = self._mapView

    for elem in _data {
        let address = elem._adress + ", " + elem._city + ", " + String(elem._zipCode) + ", France"
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(address) {
            placemarks, error in
            let placemark = placemarks?.first
            let lat = placemark?.location?.coordinate.latitude
            let lon = placemark?.location?.coordinate.longitude
            let marker = GMSMarker()
            marker.position = CLLocationCoordinate2D(latitude: lat!, longitude: lon!)
            path.add(marker.position)
            marker.title = elem._nameOfGarage
            marker.snippet = elem._adress + "\nOrdre de passege : "
            marker.map = self._mapView
        }
    }
    let rectangle = GMSPolyline(path: path)
    rectangle.strokeWidth = 4
    rectangle.strokeColor = UIColor.red
    rectangle.map = self._mapView
}

1 个答案:

答案 0 :(得分:0)

我相信你已经在https://console.developers.google.com中配置了一切。

我们可以在两个坐标之间绘制折线。您需要在已为GoogleMaps创建项目的https://console.developers.google.com上创建 ServerKey ,然后在下面的网址中使用该服务器密钥。

enter image description here

这会在两个坐标之间绘制折线。

func drawPath() {

    //Taken two source and destinations coordinates. Take the coordinates in this way. "Lat,Long" in a String
    let sourceString = "28.6562,77.2410"
    let destinationString = "27.1750,78.0422"

    //GoogleMaps Web API to draw the polyline   
    let combinedUrl : String = "https://maps.googleapis.com/maps/api/directions/json?" + "origin=\(sourceString)&destination=\(destinationString)&key=YOUR_SERVER_KEY"

    let url = URL(string:combinedUrl)

    let task = URLSession.shared.dataTask(with: url!) { (data:Data?, response:URLResponse?, error:Error?) in

        if error != nil {
            print(error.debugDescription)
            return
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary

            //We need to get to the points key in overview_polyline object in order to pass the points to GMSPath.
            let route = (((json.object(forKey: "routes") as! NSArray).object(at: 0) as! NSDictionary).object(forKey: "overview_polyline") as! NSDictionary).value(forKey: "points") as! String

            //Draw on main thread always else it will crash
            DispatchQueue.main.async {
                let path  = GMSPath(fromEncodedPath:route)!
                let polyline  = GMSPolyline(path: path)
                polyline.strokeColor = UIColor.green
                polyline.strokeWidth = 5.0

                //mapView is your GoogleMaps Object i.e. _mapView in your case
                polyline.map = self.mapView
            } 
        } catch {
        }            
    }
    task.resume()        
}

JSON 积分所需的关键数据。

enter image description here

稍后您可以使用GMSCameraPosition设置动画到绘制区域的第一个坐标。

同样对于多个点,只需在for循环中传递相应的坐标并调用drawPath函数。

您也可以查看此Video Tutorial