Skip to main content

Chapter 2: Choosing a map projection

Chapter 2: Choosing a map projection

TipAt a glance
  • In this series: Part I, Places. In Chapter 1, Indonesia covered a large part of Europe. On a web map it looks smaller. This chapter shows why, and how much different projections change sizes and shapes
  • You will build: Maps of the Earth in ten projections, a measurement of how much they change areas and shapes, and a test of which projection fits Indonesia
  • You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell
  • Time to run: The commands took less than a minute when tested. Nothing has to be downloaded
  • Level: Beginner to intermediate; most lines differ in one word only

The Earth is round, and a map is flat. A round surface cannot be made flat without stretching some parts of it. So every flat map of the world has errors in sizes, in shapes, or in both.

In Chapter 1, Indonesia reached across a large part of Europe. On the map in your phone it looks smaller than that. The reason is the projection: the calculation that turns longitude and latitude into positions on a flat map. It decides where the map is cut, and where it is stretched.

In GDAL, the projection is one short text after -t_srs. This chapter changes that text several times, compares the maps, and measures their errors. At the end you can choose a projection for your own map.

NoteLearning objectives

By the end of this chapter you will be able to:

  • change the projection of a map by changing one word;
  • draw circles of equal size on the globe, and use them to see and to measure the errors of a projection;
  • draw the shortest way between two places, and choose the projection in which it is a straight line;
  • put your own country into the middle of a world map, and repair the shapes that cross the edge;
  • choose a projection for a job by its measured errors, and find the UTM zone of a place;
  • recognise an old datum, which moves positions by more than a hundred metres.

Before running this chapter, do section 1 of Chapter 0 and section 5 of Chapter 1. In a terminal, make a new empty folder and copy into it the files of sample-data/ch02. In this notebook, the next cell does that.

import sys
import time
from pathlib import Path

# The repository root, whether the notebook runs from en/, id/ or the root itself
ROOT = Path.cwd() if (Path.cwd() / "tutorial.yml").exists() else Path.cwd().parent
sys.path.insert(0, str(ROOT / "src"))
import oneline

T0 = time.perf_counter()
WORK = oneline.start("02")
print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT / "sample-data/ch02").iterdir()))
working folder: ch02 | files copied there: ['cities.csv', 'land.geojson', 'marks.txt', 'world.tif', 'world.txt']

Warm-up

world.tif has the height of the land and the depth of the sea, with a cell every 0.15 degrees. Give the heights a colour:

gdal raster color-map world.tif plain.tif --color-map world.txt --overwrite

The whole Earth as a rectangle: blue seas with their ridges, green and brown land, and white ice. America is on the left and Australia on the right.

The map is a rectangle, twice as wide as it is high. This is the simplest way to draw the world: longitude goes to the right, and latitude goes up. Now a command that you know from Chapter 0, gdalwarp. -t_srs sets the projection of the result:

gdalwarp -q -overwrite -t_srs "+proj=bonne +lat_1=90 +lon_0=118" -ts 900 0 -r bilinear -et 0 -wo SAMPLE_STEPS=ALL plain.tif heart.png

The whole world on a black background, in the shape of a heart, with Asia in the upper middle, Indonesia and Australia below it, Africa on the left, North America at the top right, and Antarctica at the bottom.

The numbers are the same, and the map now has the shape of a heart. No part of the Earth is missing. The map is cut along one meridian through America, and this meridian forms the outer edge.

Part Meaning
+proj=bonne the name of the projection. PROJ, the library that GDAL uses, has more than a hundred, and proj -l lists them
+lat_1=90 a setting of this projection. With 90, the North Pole is at the notch at the top
+lon_0=118 the longitude in the middle: Indonesia
-ts 900 0 the picture is 900 pixels wide. The 0 means: calculate the height
-et 0 calculate every pixel exactly, and do not interpolate between pixels
-wo SAMPLE_STEPS=ALL check all positions when GDAL looks for the part of the Earth that is needed. Without it, the picture has a hole

Try it now. Change +proj=bonne +lat_1=90 to +proj=sinu, to +proj=robin or to +proj=ortho, and compare the pictures. The following sections use the same command with other projections, and measure the results.

1. Every flat world map has a cut

First make a better picture of the Earth. Four short lines enlarge it, colour it, calculate the shading, and combine colour and shading:

gdal raster resize world.tif big.tif --size 3600,1800 -r cubic --overwrite

gdal raster color-map big.tif colour.tif --color-map world.txt --overwrite

gdal raster hillshade big.tif shade.tif -z 30 --overwrite

gdal raster blend colour.tif shade.tif globe.tif --operator hsv-value --overwrite

+proj=ortho shows the Earth as it looks from very far away:

gdalwarp -q -overwrite -t_srs "+proj=ortho +lat_0=-2 +lon_0=118" -ts 800 800 -r bilinear -et 0 -wo SAMPLE_STEPS=ALL globe.tif ball.png

The Earth as a ball on black, seen from above Indonesia. The floor of the Indian Ocean has long ridges, Australia lies at the bottom, and Asia bends away at the top.

This picture shows only half of the Earth. Near the rim, everything is compressed: compare Australia and China with the rectangle in the warm-up.

The surface of a ball has no edge. A flat map of the whole world always has one, so the surface must be cut somewhere. In the heart-shaped map, the cut runs through America. In the rectangle, it runs through the Pacific, from pole to pole.

2. Fifty-five circles of equal size

To see where a map is stretched, draw shapes on the globe that have the same size everywhere. Here are 55 circles, each with a radius of 700 km:

ogr2ogr -overwrite marks.gpkg cities.csv -dialect SQLite -sql "with recursive a(i) as (select 0 union all select i+5 from a where i<360) select x, y, st_makepolygon(st_addpoint(makeline(st_project(makepoint(x,y,4326),700000,radians(i))), st_project(makepoint(x,y,4326),700000,0))) geom from (select lon.value x, lat.value y from json_each(json_array(-150,-120,-90,-60,-30,0,30,60,90,120,150)) lon, json_each(json_array(-60,-30,0,30,60)) lat), a group by x, y" -nln circle -nlt POLYGON -a_srs EPSG:4326

ogr2ogr -f CSV /vsistdout/ marks.gpkg -sql "select abs(y) latitude, count(*) circles, round(avg(st_area(geom,1))/1e6) square_km from circle group by 1"
latitude,circles,square_km
0,11,1535892
30,22,1535897
60,22,1535907

st_project(point, distance, direction) calculates the point that is 700 km away from the centre in one direction, on the curved Earth. The query does this for a direction every 5 degrees, and makeline connects the points.

The table confirms the size. st_area(geom,1) measures on the curved Earth, and every circle has about 1.54 million square kilometres, at the equator and in the north.

Now draw the circles on the map as yellow rings, and calculate two projections of it:

gdal pipeline read marks.gpkg ! sql --dialect SQLite "select 1 v, st_buffer(st_boundary(geom),0.35) geom from circle" ! rasterize --attribute-name v --init 0 --ot Byte --size "7200,3600" --extent "-180,-90,180,90" ! edit --nodata none ! color-map --color-map marks.txt --add-alpha --color-selection nearest ! materialize ! resize --size "3600,1800" -r average ! write rings.tif --overwrite

gdal raster blend globe.tif rings.tif dots.tif --overwrite

gdalwarp -q -overwrite -t_srs "+proj=merc" -te -20037508 -15000000 20037508 15000000 -ts 1000 0 -r bilinear -et 0 -wo SAMPLE_STEPS=ALL dots.tif mercator.png

gdalwarp -q -overwrite -t_srs "+proj=moll" -ts 1100 0 -r bilinear -et 0 -wo SAMPLE_STEPS=ALL dots.tif mollweide.png

The world in the Mercator projection with yellow rings. All rings are round, but those in the far north and south are twice as wide as those at the equator. Greenland is so large that it reaches out of the picture.

The world as an ellipse with the same yellow rings. They all cover the same area, but towards the edges and the poles they lean over and become slanted ovals.

Look before moving on. The two projections have different errors.

  • Mercator (1569) keeps the shape of small areas. The rings are round everywhere. The sizes are wrong: the farther from the equator, the larger everything is drawn.
  • Mollweide keeps the sizes. All rings cover the same area. The shapes are wrong: far from the middle of the map, the rings become slanted ovals.

No flat map can keep both, everywhere. Only a globe keeps all shapes and all sizes.

3. How large are the errors?

The errors can be measured. Take the rings in the middle column, project them, and calculate their area and their shape. There are three lines, and they differ in one word only:

gdal vector pipeline read marks.gpkg --input-layer circle ! reproject --dst-crs "+proj=merc +datum=WGS84" ! sql --dialect SQLite "select abs(y) latitude, round(100*avg(st_area(geom))/1535892e6) area_percent, round(avg((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),2) width_by_height from circle where abs(x)<1 group by 1" ! write /vsistdout/ --output-format CSV

gdal vector pipeline read marks.gpkg --input-layer circle ! reproject --dst-crs "+proj=moll +datum=WGS84" ! sql --dialect SQLite "select abs(y) latitude, round(100*avg(st_area(geom))/1535892e6) area_percent, round(avg((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),2) width_by_height from circle where abs(x)<1 group by 1" ! write /vsistdout/ --output-format CSV

gdal vector pipeline read marks.gpkg --input-layer circle ! reproject --dst-crs "EPSG:4087" ! sql --dialect SQLite "select abs(y) latitude, round(100*avg(st_area(geom))/1535892e6) area_percent, round(avg((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),2) width_by_height from circle where abs(x)<1 group by 1" ! write /vsistdout/ --output-format CSV
latitude,area_percent,width_by_height
0,100,1
30,134,1
60,407,0.99
latitude,area_percent,width_by_height
0,101,0.81
30,100,0.9
60,100,1.36
latitude,area_percent,width_by_height
0,101,0.99
30,116,1.15
60,201,2.01

area_percent is 100 if the size is right. width_by_height is 1 if the ring is still round.

Size at 60 degrees Shape at 60 degrees It keeps
Mercator 4 times too large round the shape
Mollweide right a third too wide the size
EPSG:4087, the simple rectangle of the warm-up twice too large twice as wide as high neither

The simple rectangle keeps neither sizes nor shapes. It is still useful, because the longitude and latitude of a cell follow directly from its column and row.

Web maps in phones and browsers use a form of Mercator with the number EPSG:3857. Use the coast lines to calculate the area of six islands, on the Earth and on such a map:

ogr2ogr -f CSV /vsistdout/ land.geojson -dialect SQLite -sql "select name, round(st_area(geometry,1)/1e6) true_km2, round(st_area(st_transform(geometry,3857))/1e6) web_map_km2, round(st_area(st_transform(geometry,3857))/st_area(geometry,1),1) times from land, (select 'Sumatra' name, 102 x, -1 y union all select 'Great Britain', -1.5, 52.5 union all select 'Java', 110, -7.2 union all select 'Iceland', -18.5, 65 union all select 'Greenland', -40, 72 union all select 'Borneo', 114, 0) where st_intersects(geometry, makepoint(x,y,4326)) order by 2 desc"
name,true_km2,web_map_km2,times
Greenland,2206496,36284875,16.4
Borneo,745074,751645,1
Sumatra,439988,444078,1
Great Britain,238023,686905,2.9
Java,137711,140937,1
Iceland,107800,605657,5.6

Look before moving on. On the web map, Great Britain is half as large again as Sumatra. On the Earth, Sumatra is almost twice as large as Great Britain. Iceland is drawn four times as large as Java, although it is smaller.

This answers the question of Chapter 1. The web map enlarges the countries in the far north. Indonesia lies on the equator and is drawn almost in its true size, so it looks small beside them. (The coast lines here are very simple, so the areas are approximate. This has little effect on the last column, because both areas come from the same coast line.)

4. The shortest way to Mecca

In which direction is Mecca from Indonesia? And is a straight line on the map the shortest way? The file cities.csv has 14 cities. This query calculates the shortest way over the curved Earth for each of them, in 200 steps:

ogr2ogr -update -overwrite marks.gpkg cities.csv -oo AUTODETECT_TYPE=YES -dialect SQLite -sql "with recursive s(i) as (select 0 union all select i+1 from s where i<200), c as (select name, makepoint(lon,lat,4326) p, makepoint(39.8262,21.4225,4326) m from cities) select name, degrees(st_azimuth(p,m)) direction, degrees(st_azimuth(st_transform(p,3857),st_transform(m,3857))) ruler, st_distance(p,m,1)/1000 km, makeline(st_project(p,st_distance(p,m,1)*i/200,st_azimuth(p,m))) geom from c, s group by name" -nln way -nlt LINESTRING -a_srs EPSG:4326

ogr2ogr -f CSV /vsistdout/ marks.gpkg -sql "select name, round(km) km, round(direction,1) direction, round(ruler,1) ruler from way order by km"
name,km,direction,ruler
BANDA ACEH,6224,292.1,286.4
MEDAN,6649,292.7,287.3
PADANG,7025,294.6,290.7
PONTIANAK,7898,292.6,287.5
JAKARTA,7919,295,292.8
SURABAYA,8564,293.9,291.8
BALIKPAPAN,8722,292.1,286.8
MAKASSAR,9153,292.4,288.8
MANADO,9441,291.3,283.5
KUPANG,9788,292.1,291
AMBON,9998,291.4,286.2
SORONG,10202,291.3,284
JAYAPURA,11245,291.3,283.6
MERAUKE,11447,290.1,286.9
Part Meaning
st_azimuth(p,m) the direction from one point to the other, here on the curved Earth. 0 is north, 90 is east, 270 is west
st_distance(p,m,1) the distance on the curved Earth, in metres
distance*i/200 the distance of each step from the start
ruler the direction of a straight line drawn on the web map. st_transform(p,3857) gives the position on that map

The direction is different for every city, between 290 and 295 degrees. That is a little north of west. The straight line on the web map has a smaller angle, by one degree in Kupang and by almost eight in Manado. For places far from the equator, the difference can be much larger, and the exercises have an example.

Draw the lines on the map, and calculate two projections of it, as before:

gdal pipeline read marks.gpkg ! sql --dialect SQLite "select 2 v, st_buffer(geom,0.2) geom from way union all select 1, st_buffer(st_startpoint(geom),0.8) from way union all select 3, st_buffer(makepoint(39.8262,21.4225),1.1)" ! rasterize --attribute-name v --init 0 --ot Byte --size "7200,3600" --extent "-180,-90,180,90" ! edit --nodata none ! color-map --color-map marks.txt --add-alpha --color-selection nearest ! materialize ! resize --size "3600,1800" -r average ! write rays.tif --overwrite

gdal raster blend globe.tif rays.tif ways.tif --overwrite

gdalwarp -q -overwrite -t_srs "+proj=merc" -te 2600000 -2500000 16800000 4500000 -ts 1100 0 -r bilinear -et 0 -wo SAMPLE_STEPS=ALL ways.tif ways_mercator.png

gdalwarp -q -overwrite -t_srs "+proj=gnom +lat_0=8 +lon_0=92" -te -9800000 -4000000 8600000 4600000 -ts 1100 0 -r bilinear -et 0 -wo SAMPLE_STEPS=ALL ways.tif ways_straight.png

The Indian Ocean in the Mercator projection. Fourteen red lines run from yellow dots in Indonesia to a white dot in Arabia, and all of them bend a little to the north.

The same region in the gnomonic projection. Asia and the ocean floor are stretched towards the corners, and the fourteen red lines are perfectly straight.

Look before moving on. In the first map, the shortest ways are curved. In the second map, the same lines are straight.

The second projection is called gnomonic. It shows every shortest way as a straight line (the PROJ manual says “approximately”, because the Earth is not exactly a ball). It has two disadvantages: it can show less than half of the Earth, and the enlargement grows without limit towards the edge. So it is not suitable for comparing the sizes of countries. Use it to find shortest ways.

On a Mercator map, a straight line is a way with a constant compass direction. A ship can follow it without changing its compass direction, but the way is a little longer than the shortest one. This is why the projection was useful for navigation at sea.

Check the direction with a second method. In the projection aeqd, all directions and distances from the centre are right. Set Jakarta as the centre, and calculate the position of Mecca:

gdaltransform -output_xy -s_srs EPSG:4326 -t_srs "+proj=aeqd +lat_0=-6.17 +lon_0=106.83 +datum=WGS84" -coord 39.8262 21.4225
-7175947.34398624 3348757.07329647

Mecca is 7,176 km to the west and 3,349 km to the north. With the theorem of Pythagoras, the distance is 7,919 km, and the angle is 295.0 degrees. The query above gave the same result.

5. Put Indonesia in the middle

On most world maps, Europe and Africa are in the middle, and Indonesia is near the right edge. This is only a convention. +lon_0=118 changes it. +proj=eqearth is a projection of 2018 that keeps the sizes right. Project the coast lines, and draw them as white shapes:

gdal vector reproject land.geojson torn.gpkg --dst-crs "+proj=eqearth +lon_0=118 +datum=WGS84" --overwrite

gdal vector rasterize torn.gpkg torn.tif --burn 255 --ot Byte --size 1200,584 --extent "-17243960,-8392928,17243960,8392928" --overwrite

gdal raster edit torn.tif --nodata none

gdal raster convert torn.tif torn.png --overwrite

A map of the world in white on black with errors. A huge white band runs across the whole width at the height of South America, and thinner white stripes cross the north.

This is a common error. It often happens when the middle of a map is moved. The cause is the following.

The new map is cut on the other side of the Earth, at 118 - 180 = 62 degrees west. This line runs through South America. But the polygon of South America was not cut. Some of its points are at the left edge of the map and others at the right edge, and the sides between them cross the whole map.

So cut the polygons first, and project them afterwards. Take the part to the west of the line and the part to the east of it:

ogr2ogr -overwrite cut.gpkg land.geojson -dialect SQLite -sql "select st_intersection(st_makevalid(geometry), buildmbr(-180,-90,-62.001,90,4326)) geom from land union all select st_intersection(st_makevalid(geometry), buildmbr(-61.999,-90,180,90,4326)) from land" -nln land -nlt PROMOTE_TO_MULTI

gdal vector pipeline read cut.gpkg ! segmentize --max-length 1 ! reproject --dst-crs "+proj=eqearth +lon_0=118 +datum=WGS84" ! write whole.gpkg --overwrite

gdal vector rasterize whole.gpkg whole.tif --burn 255 --ot Byte --size 1200,584 --extent "-17243960,-8392928,17243960,8392928" --overwrite

gdal raster edit whole.tif --nodata none

gdal raster convert whole.tif whole.png --overwrite

The repaired map. Indonesia and Australia are in the middle, the Pacific is one open space to the right, the Americas are at the right edge, and the eastern part of South America is at the left edge.

Part Meaning
buildmbr(-180,-90,-62.001,90,4326) a box from 180 degrees west to just before the cut. A very small gap separates the two sides
st_makevalid repairs polygons that cross themselves. Without it, the cut can fail
segmentize --max-length 1 adds a point at every degree. The new edge is a line of 180 degrees with two points. Such a line stays straight, but the edge of the map is curved

Look before moving on. The Pacific is now in one piece. The way from Indonesia to America across the Pacific is short on this map. On a map with Europe in the middle, the Pacific is cut in two.

A raster does not have this problem, because it has no polygons whose sides could cross the map. That is why gdalwarp needed no cut.

6. More cuts, smaller errors

So far, the world was cut in one place only. With more cuts, each piece is smaller and is stretched less. For a map of the oceans, the cuts run through the land:

gdalwarp -q -overwrite -t_srs "+proj=igh_o +lon_0=-160" -ts 1100 0 -r bilinear -et 0 -wo SAMPLE_STEPS=ALL globe.tif lobes.png

The world on black, cut into pieces. Three wide parts are connected at the equator, with the Indian Ocean, the Pacific and the Atlantic in their middles, and the cuts run through the land.

J. P. Goode published this projection in 1925. It keeps all sizes, like Mollweide, and the shapes are much better. The disadvantage is that the land is cut: Australia and the Americas are in several pieces, and Indonesia is connected only by a narrow strip between two parts.

For the next projection, the surface of the Earth is projected onto 20 triangles, and the triangles are then laid flat. Buckminster Fuller began with this idea in 1943. The cuts mostly run through the sea. (SOURCE_EXTRA=100 reads 100 pixels more on every side. Without it, the South Pole has a hole.)

gdalwarp -q -overwrite -t_srs "+proj=airocean +orient=horizontal" -ts 1100 0 -r bilinear -et 0 -wo SAMPLE_STEPS=ALL -wo SOURCE_EXTRA=100 globe.tif fold.png

A net of triangles on black. Africa, Europe, Asia, North and South America and Antarctica form one long chain from the top left to the right, Australia lies at the bottom left near Indonesia, and the oceans are at the sides.

Look before moving on. Start from Indonesia. Asia is connected to Europe and Africa on one side, and to the Americas on the other, with only the narrow Bering Strait between them. On this map, the land is almost one connected area. The islands of Indonesia lie between Asia and Australia.

You can make a small globe from this map. Print it, cut it out along its outline, fold it at the sides of the triangles, and tape it together. The globe has 20 faces. (Some triangles are cut in two, so that a piece of land stays whole. Join their halves with tape.)

7. All oceans in one piece

The next projection does the opposite of the last one. Its cuts run through the land, and the water stays connected. It is named after the ocean scientist Athelstan Spilhaus:

gdalwarp -q -overwrite -t_srs "+proj=spilhaus" -ts 900 0 -r bilinear -et 0 -wo SAMPLE_STEPS=ALL globe.tif ocean.png

A square map in which all the oceans form one connected blue body of water, with Antarctica near the centre. Asia and the Americas lie around the edge like a frame, and are stretched beyond recognition.

Look before moving on. Antarctica is near the middle, and the Atlantic, the Indian Ocean and the Pacific form one connected area of water around it.

Indonesia lies between the Pacific and the Indian Ocean, to the north of Australia. Warm water from the Pacific flows through its straits into the Indian Ocean, and it is the only connection of this kind in the tropics. On other maps, this is harder to see. So the projection also decides which connections are easy to see.

(The land near the edge is enlarged without limit, and in the two black corners PROJ cannot calculate a position. This map is not suitable for China or Argentina.)

8. Which projection for Indonesia?

Most maps show a city, an island or a country, and not the whole world. To find a suitable projection for Indonesia, test some of them with the method of section 3. The circles are smaller this time, with a radius of 20 km, and there is one every two degrees over all of Indonesia:

ogr2ogr -overwrite id.gpkg cities.csv -dialect SQLite -sql "with recursive a(i) as (select 0 union all select i+10 from a where i<360), g(x) as (select 95 union all select x+2 from g where x<141), h(y) as (select -11 union all select y+2 from h where y<6), c as (select x, y, st_makepolygon(st_addpoint(makeline(st_project(makepoint(x,y,4326),20000,radians(i))), st_project(makepoint(x,y,4326),20000,0))) geom from g, h, a group by x, y) select x, y, st_area(geom,1) true_m2, geom from c" -nln spot -nlt POLYGON -a_srs EPSG:4326

gdal vector pipeline read id.gpkg ! reproject --dst-crs "EPSG:3857" ! sql --dialect SQLite "select round(100*min(st_area(geom)/true_m2),1) least, round(100*max(st_area(geom)/true_m2),1) most, round(min((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),3) narrowest, round(max((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),3) widest from spot" ! write /vsistdout/ --output-format CSV

gdal vector pipeline read id.gpkg ! reproject --dst-crs "EPSG:32748" ! sql --dialect SQLite "select round(100*min(st_area(geom)/true_m2),1) least, round(100*max(st_area(geom)/true_m2),1) most, round(min((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),3) narrowest, round(max((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),3) widest from spot" ! write /vsistdout/ --output-format CSV

gdal vector pipeline read id.gpkg ! reproject --dst-crs "+proj=cea +datum=WGS84" ! sql --dialect SQLite "select round(100*min(st_area(geom)/true_m2),1) least, round(100*max(st_area(geom)/true_m2),1) most, round(min((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),3) narrowest, round(max((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),3) widest from spot" ! write /vsistdout/ --output-format CSV

gdal vector pipeline read id.gpkg ! reproject --dst-crs "+proj=laea +lat_0=-2.5 +lon_0=118 +datum=WGS84" ! sql --dialect SQLite "select round(100*min(st_area(geom)/true_m2),1) least, round(100*max(st_area(geom)/true_m2),1) most, round(min((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),3) narrowest, round(max((st_maxx(geom)-st_minx(geom))/(st_maxy(geom)-st_miny(geom))),3) widest from spot" ! write /vsistdout/ --output-format CSV
least,most,narrowest,widest
100.7,104.4,0.993,0.994
least,most,narrowest,widest
99.9,153.2,1,1
least,most,narrowest,widest
100,100,1,1.038
least,most,narrowest,widest
100,100,0.96,1.007

least and most are the smallest and the largest circle, in percent of the true size. narrowest and widest are the width divided by the height of the narrowest and of the widest circle, and 1 is round.

Projection Sizes in Indonesia Shapes Use it for
EPSG:3857, the web map up to 4.4 percent too large good a background map in a browser, and no measurements
EPSG:32748, UTM zone 48 south right around Jakarta, 53 percent too large in Papua right a city or a district in this zone
+proj=cea, an equal-area projection on a cylinder right everywhere at most 4 percent too wide areas, densities, statistics of the country
+proj=laea with the centre in Indonesia right everywhere at most 4 percent too narrow the same, and general maps

Two results are important.

The errors of the web map are small in Indonesia, because the country lies along the equator. A web map of Norway makes the areas 3 to 9 times too large, and one of Indonesia at most 4 percent.

A UTM zone is not suitable for a whole country of this size. A zone is 6 degrees wide, and Indonesia reaches from zone 46 to zone 54. Inside its zone, UTM has very small errors. Far outside the zone, the errors are large, and there is no warning. To find the zone of a place, divide the longitude by 6 degrees:

ogr2ogr -f CSV /vsistdout/ cities.csv -oo AUTODETECT_TYPE=YES -dialect SQLite -sql "select name, cast((lon+186)/6 as integer) zone, case when lat<0 then 'south' else 'north' end half, case when lat<0 then 32700 else 32600 end+cast((lon+186)/6 as integer) epsg from cities"
name,zone,half,epsg
BANDA ACEH,46,north,32646
MEDAN,47,north,32647
PADANG,47,south,32747
PONTIANAK,49,south,32749
JAKARTA,48,south,32748
SURABAYA,49,south,32749
BALIKPAPAN,50,south,32750
MAKASSAR,50,south,32750
KUPANG,51,south,32751
MANADO,51,north,32651
AMBON,52,south,32752
SORONG,52,south,32752
JAYAPURA,54,south,32754
MERAUKE,54,south,32754

First decide what must be right, and then choose the projection.

What must be right Choose For example
Areas: forest, rice, people per km² an equal-area projection cea, laea, eqearth, moll
Angles and shapes of a small region, short distances a conformal one the UTM zone of the place
Distance and direction from one place aeqd, with this place as the centre a radio mast, an airport, an epicentre
Shortest ways as straight lines gnom a flight, the way to Mecca
A number, and no picture none. Measure on the curved Earth st_area(geom,1), st_distance(a,b,1)

The last row is often forgotten. If you only need a number, you do not need a projection.

9. An old datum moves a place by 168 metres

Longitude and latitude alone do not define a place. They also need a datum. The National Monument in Jakarta, Monas, is at 106.8272 east, 6.1754 south. Suppose that you read the same numbers from an old map with the datum Batavia. Where is this point on a map of today?

gdaltransform -output_xy -s_srs EPSG:4211 -t_srs EPSG:4326 -coord 106.8272 -6.1754

ogr2ogr -f CSV /vsistdout/ cities.csv -dialect SQLite -sql "select datum, epsg, round(st_distance(makepoint(106.8272,-6.1754,4326), st_transform(makepoint(106.8272,-6.1754,epsg),4326),1)) moved_m from (select 'Batavia' datum, 4211 epsg union all select 'ID74, Indonesia 1974', 4238 union all select 'DGN95', 4755 union all select 'SRGI2013', 9470) limit 4"
106.828708492641 -6.17520793036197
datum,epsg,moved_m
Batavia,4211,168
"ID74, Indonesia 1974",4238,27
DGN95,4755,0
SRGI2013,9470,0

The point moves 168 metres, mostly to the east.

Longitude and latitude are angles, and they are measured on an ellipsoid, a simple model of the shape of the Earth. A datum says which ellipsoid is used, and how it is placed. Before there were satellites, every region chose the ellipsoid that fitted best in that region, and fixed it at a point there. Batavia is the old name of Jakarta, and the longitude of its observatory is one of the numbers that define this datum. The global datums of today use an ellipsoid with its centre in the centre of the Earth. The other names in the table are later datums of Indonesia: ID74 differs by 27 m, and for the two newest the difference is too small to matter on a map.

PROJ can convert between datums, and it reports how accurate each conversion is:

projinfo -s EPSG:4211 -t EPSG:4326 --summary --spatial-test intersects
Candidate operations found: 4
EPSG:8452, Batavia to WGS 84 (1), 6.0 m, Indonesia - onshore - Bali, Java and western Sumatra.
EPSG:1813, Batavia to WGS 84 (2), 5.0 m, Indonesia - southern Java Sea offshore northwest Java.
EPSG:1814, Batavia to WGS 84 (3), 5.0 m, Indonesia - offshore Madura Strait and western Bali Sea.
unknown id, Ballpark geographic offset from Batavia to WGS 84, unknown accuracy, World, has ballpark transformation

Look before moving on. There are several conversions, each with an accuracy and a region. The first one is made for Bali, Java and western Sumatra, and is accurate to about 6 m. The last one is called ballpark, which means a rough estimate. PROJ uses it if it has no parameters for the conversion, and then it leaves the numbers as they are.

So, if one layer is shifted by some 50 to 300 metres against another one, always in the same direction, the cause is probably a wrong or missing datum, and not a bad survey. Set the right one with -s_srs or gdal raster edit --crs, and the layers will match. Chapter 0 has this case in its collection.

Try it yourself

  • Another centre. Change +lon_0 in the warm-up to your own longitude. For which longitude does the cut cross the least land?
  • A long distance. Take New York (-74.0, 40.7) in section 4, in place of the 14 cities. The shortest way to Mecca begins to the north-east, and the straight line on the web map points a little south of east. Why?
  • Other projections. Try +proj=peirce_q, +proj=healpix or +proj=isea in section 6. Which of these maps can be repeated side by side without gaps?
  • South at the top. North at the top is only a convention. +proj=eqearth +lon_0=118 +axis=wsu puts the south at the top.
  • Your own island. Make the circles of section 8 only over your island, and find the projection with the smallest error.

Checkpoint

The cell below stops with an error if the results are not what this chapter expects.

import csv
import io

def rows(sql, dataset):
    """The rows of a query, as dictionaries."""
    return list(csv.DictReader(io.StringIO(oneline.run(f'ogr2ogr -f CSV /vsistdout/ {dataset} -dialect SQLite -sql "{sql}"'))))

areas = [float(r["a"]) for r in rows("select st_area(geom,1) a from circle", "marks.gpkg")]
assert len(areas) == 55 and max(areas) / min(areas) < 1.001, "55 circles of equal size"

jakarta = rows("select direction d, km from way where name='JAKARTA'", "marks.gpkg")[0]
assert abs(float(jakarta["d"]) - 295.0) < 0.1 and abs(float(jakarta["km"]) - 7919) < 5

# The torn map has a shape that is as wide as the world, and the repaired one does not
wide = [float(rows("select sum(w>30e6) n from (select st_maxx(g)-st_minx(g) w from (select geom g from " + t + "))", f)[0]["n"]) for t, f in (("land", "torn.gpkg"),)]
assert wide[0] >= 1

pictures = ("heart.png", "ball.png", "mercator.png", "mollweide.png", "ways_mercator.png", "ways_straight.png", "lobes.png", "fold.png", "ocean.png")
assert all((WORK / f).stat().st_size > 10_000 for f in pictures)
print(f"checkpoint passed: 55 equal circles; Jakarta to Mecca {float(jakarta['km']):,.0f} km at {float(jakarta['d']):.1f} degrees; {len(pictures)} maps")
print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: 55 equal circles; Jakarta to Mecca 7,919 km at 295.0 degrees; 9 maps
time since the first cell: 51 s

Troubleshooting

Symptom Cause Fix
Wide stripes across the whole map Shapes cross the line where the new map is cut Cut them there first, and then project, as in section 5
Holes or missing corners in a projection with several cuts gdalwarp estimated which part of the Earth it needs, and missed some of it -et 0 -wo SAMPLE_STEPS=ALL
reproject reports an error about a datum or an unknown source A text such as +proj=merc does not contain a datum Add +datum=WGS84
A picture that is extremely high On a Mercator map, the poles are infinitely far away Give a window with -te
No transform operation found, or inf The projection cannot show the place, such as the other side of the Earth with gnom Another centre, or another projection
Two layers differ by 50 to 300 m Two datums Find out the old one, and set it as the source

What comes next

You can now choose a projection and measure its errors. The same tools work for the sky, because the position of a star is also given by two angles. Chapter 3: Maps of the night sky makes maps of the stars.

Relief: C. Amante and B. W. Eakins, ETOPO1 1 Arc-Minute Global Relief Model, NOAA Technical Memorandum NESDIS NGDC-24, 2009, doi:10.7289/V5C8276M. Coast lines: Natural Earth, in the public domain. Projections: PROJ.