How To Avoid Places

  • keywords:
    • software
    • python
    • cartopy
    • matplotlib
    • shapely
    • naturalearth
  • published:
  • updated:
  • Atom Feed

The eagle-eyed amongst you may have noticed something interesting in : I chose to highlight some countries in particular (the UK and the US) and I chose to call this list avoids in the source code (line 19).

Whilst the previous script did indeed easily display where the antipode of any point was (thus helping me to find that Tasmania would be a great bet) it did have one huge flaw if it was to be used to avoid places: it would only tell you how to avoid a point. The script was not helpful at all at telling you how to avoid an area, such as a country: I therefore set out to write version 2 of my script.

My chosen method was to expand the coastlines of a list of countries by set distances. By successively increasing the coastlines I would create an area on the far side of the Earth that was further away than the expanded coastline (or indeed outside this “exclusion zone”). I could then increase the distance until there was nowhere left on the surface of the Earth that was that far away from the coastlines. The technical term for such an operation is to buffer an object and Shapely has a function to do just that.

Unfortunately, the Shapely function has no knowledge that it is being used to describe areas on the surface of the Earth: it is just a library that describes shapes. Consequently, the buffer function expands objects by whatever unit the object is described in, in this case: degrees. This poses a major problem: the length of a degree changes depending on where you are in the world and which direction you would like to go. Additionally, it has no knowledge of the anti-meridian and the problem that it poses. What I needed was a function that took in an area defined in degrees and buffered it by a single distance in kilometres: the resultant object would be buffered by a varying amount in units of degrees but by a constant amount in units of kilometres. For this script to work I wrote two functions:

Once these two functions were written (and extra logic was added to deal with areas overlapping the anti-meridian) it was relatively easy to buffer the coastlines of the UK and the US and find out where in the world to go if you wanted to avoid them. Below is the script that I wrote that uses these two functions (I found that simplifying the polygons whenever I could drastically reduced runtime).

To view this source code snippet without JavaScript you can either download “” directly or view “” on GitHub Gist.

The image produced by this script is shown below.

  1. 512x267 (214.1 KiB)
  2. 1,024x533 (758.5 KiB)
  3. 2,048x1,067 (2.5 MiB)
  4. 2,152x1,121 (2.4 MiB)

A couple of things strike me when I look at this image: