1

I tried to implement differents solutions for draw polyLines between markers on my GMSMapView but is not working. Do you have others solutions or maybe do you know what's wrong in my code ?

    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
}
Millet Antoine
  • 405
  • 1
  • 6
  • 24

1 Answers1

1

I believe you have configured everything fine in https://console.developers.google.com.

We can draw a polyline between two coordinates. You need to create your ServerKey on https://console.developers.google.com where you have created your project for GoogleMaps and then use that Server Key in the URL below.

enter image description here

This draws polyline between two coordinates.

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 points key data required.

enter image description here

Later on you can animate to the drawn region first coordinate using the GMSCameraPosition.

Similarly for multiple points, just pass the respective coordinates in a for loop and call drawPath function.

You can have a look at this Video Tutorial too.

Rajan Maheshwari
  • 14,465
  • 6
  • 64
  • 98