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.
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!
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!
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.
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.
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.
To have a look at the full code with comments and play – see here