Directed GMSPolyline

Muhammad Zeeshan
2 min readFeb 12, 2020

In this tutorial we are going to draw a directed polyline (draw small direction arrow) by using Google Maps iOS SDK. The end result will look like the following screenshot.

Final Result

I am assuming you have setup the google maps iOS SDK for your project. For the sake of simplicity for this tutorial i will be using hard coded geo json. GeoJSON is a format for encoding a variety of geographic data structures which may contains array of array which consists longitude and latitude. I repeat longitude and latitude.

The GeoJSON used in this tutorial can be found here.

Steps to draw directed polyline

  • Step 1: Convert Geo JSON into array of ‘CLLocationCoordinate2D’.
  • Step 2: Next we need to determine a point where we need to add direction arrow. Right now there are 2 approaches in my mind i.e. Distance based, Geo location point based. For this tutorial I will be using point based approach. For this approach, define a chunk size that fits best for your needs. I will be using 3 as a chunk size. So, create chunks of the coordinates array. I am using the following extension for making the chunks of array, found here.
  • Step 3: Create an instance of ‘GMSMutablePath’ that will be used as an input to ‘GMSPolyline’ instance.
  • Step 4: Iterate through the chunked coordinates and add ‘GMSMarker’ for specified position. Don’t forgot to set ‘isFlatto true. ‘isFlat’ is false by default which means when you rotate map the marker will keep its position as it is i.e. face up. In our case we want our markers to remain stick with the surface.
  • These markers will be serve as an arrow. Mean while append the coordinates in the created instance of ‘GMSMutablePath’. The coordinates that we are adding in our path will used to draw a joined line on the map.
  • Next we are adding some filters to make sure that the point which is selected for the arrow should not be too closed with each other. Moreover we need to make sure that the point that is selected for the arrow should be on the polyline.
  • Further more, we need to make sure that the rotation angle of our ‘GMSMarker’ should be align with the heading direction. So, we calculate the angle by using helper function provided in the Google Maps SDK i.e. ‘GMSGeometryHeading’. If you are curious to know how things works, goto this link.
  • Step 5: Create an instance of ‘GMSPolyline’ by passing the instance of path in the initialiser. Adjust the colour and stroke according to your needs.
  • Step 6: Zoom to fit the final result. That’s it!

Code snippet for the steps mentioned above is

Function for drawing directed polyline

Here is final code. Enjoy!

--

--