BlogsOpenLayers

Puzzling with OpenLayers and Turf.js

By 27 June 2018April 3rd, 2023No Comments

In this blog post I’ll talk about a few interesting bits of a puzzle made with OpenLayers and Turf.js. It is a puzzle of the world with the goal to drag the shapes of countries back in the right place. Many hours were spent trying to solve the puzzle myself and I realised I needed some tools to help me finish it.

puzzle-overview.PNG

Prep

For the map part of the puzzle we are using OpenLayers. For doing a bit of geospatial analysis in the browser we are using Turf.js.

The following data was used:

  • Background tiles – I picked the aerial layer from Bing Maps which doesn’t show the border of countries.
  • Countries of the world in vector format – I am using a sample GeoJSON provided by OpenLayers. The vectors are very generalised which is a good thing in our case because it makes it quicker to do calculations on the vectors. Only 179 countries exist according to this dataset however!

Start game

To start the game we need to randomise the location of the countries. OpenLayers has a translate function on an individual geometry which modifies the geometry coordinates. It needs a delta for both the X and Y axis. A plain JavaScript function can give us random integers to generate the X and Y axis. By iterating over every country in the dataset, and applying a random offset to it, we can shuffle the countries. The player can now try and put them back in the right place.

Match?

Turf.js is used to decide if the puzzle piece is in the right place. The centre of the puzzle piece is compared to the centre of the actual country. The distance between the two is calculated with Turf.js after transforming the coordinates to latitude and longitude. If the distance is smaller than 1000 km, then it is considered a match!

Help!

The large countries are easy to locate but after 50 countries, it gets more difficult! To help the frustrated puzzler, I added a few tools.

Spyglass

Since seeing a spyglass code example on the OpenLayers page, I have been wanting to use it and I found a use for it in the puzzle.  A reference layer has been added to the map which shows all the country borders. It is hidden behind another layer but the spyglass allows the player to see a bit of it. It is using the HTML5 canvas and the ‘precompose’ event on the reference layer.

spy-glass.PNG

Find the last pieces

I couldn’t place the last tiny puzzle pieces without help. To actually find the last puzzle pieces floating around on the map, the ‘Zoom to next puzzle piece’ is handy. It looks at the remaining countries and zooms to the first country that is comes across.

The ‘List remaining countries’ simply lists the remaining countries so you know where the last pieces need to go.

Play

To have a look at the full code with comments and play – see here