Decoding a polyline, and drawing it with SwiftUI (MapKit)

Mauricio Vazquez
2 min readMay 8, 2020

--

I recently needed to draw a polyline in a SwiftUI project. I didn’t found any information so I thought I would write in case it helps someone in the future. The main goal is to draw a polyline on a MapKit view. We’re going to draw this from an encoded polyline string, which we´ll then decode into an array of location coordinates.

The first thing we need to do is create a brand new “Single View App”, making sure SwiftUI is selected as the user interface. I will follow the MVVM pattern in this example just for the sake of being a little bit organized. You can do it how it’s more convenient.

First thing I did was create the following files:

I renamed ContentView to MapView so you got to make sure to change it in SceneDelegate as well.

The next thing I did was to add the Polyline library which you can easily add to your project with Swift Package Manager, Cocoapods, etc… If you don’t want to install a library, I saw a few alternatives here.

In the MapViewCoordinator.swift file, we´ll add the following code

An important function here in the coordinator is rendererFor. This is where you set the line properties such as the line’s color and the line width.

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {

In LocationViewModel.swift we’ll decode the polyline and assign it to the location variable. In a real project, we would probably fetch it from a web service.

And finally, MapView.swift.

The first thing we do here is set the UIViewRepresentable methods where we set the coordinator and update the view. We set two private functions updateOverlays where we set the overlay and setMapZoomArea where we zoom to the whole polyline region.

Run the project and your map should look like this:

You can download the source code here: https://github.com/maurovz/MapKitPolyline

If you have any comments or you want me to write something more specific let me know!

--

--

Mauricio Vazquez

I tried playing at the digital nomad for a while. Now living in Spain and enjoying the weather!