Skip to main content

Chapter 8: The most inland place

Chapter 8: The most inland place

TipAt a glance
  • In this series: Part III, Areas. Chapter 7 drew lines in the sea at equal distances from the coast. This chapter measures the same distance on land: which place is farthest from the coast?
  • You will build: The point of Borneo that is farthest from the sea, the largest circle in every island, the point in the ocean that is farthest from land, and the area around each airport in Indonesia
  • You need: Chapter 0, for the environment, and section 5 of Chapter 1, for lines that work in every shell. About 300 MB of free space
  • Time to run: The commands took a little more than two minutes when tested, including 4 MB of downloads
  • Level: Intermediate; rasters and polygons work together

Which place on Borneo is the farthest from any coast? The question is easy to ask, but the answer is not in the data of a map. It needs the distance to the coast, calculated for every place of the island.

GDAL does this with one command. It turns a map into a map of distances. This chapter finds the most inland point of an island, then of eighteen islands at once, and then the point in the ocean that is farthest from any land, which has a name. The last part calculates the area that belongs to each airport of Indonesia.

NoteLearning objectives

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

  • turn any shape into a map of distances, with one pipeline;
  • find the place of a maximum in a raster, and its position on Earth;
  • explain why the most inland point is the middle of a circle that touches three coasts;
  • draw the shortest way to the sea from thousands of places;
  • run the same calculation for many areas at once;
  • choose a projection that keeps distances true, and check the result against a published one;
  • divide land among points, so that each place belongs to the nearest of them.

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/ch08. 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("08")
print("working folder:", WORK.name, "| files copied there:", sorted(f.name for f in (ROOT / "sample-data/ch08").iterdir()))
working folder: ch08 | files copied there: ['airports.csv', 'far.txt', 'hop.txt', 'indonesia.gpkg.zip', 'ink.txt', 'islands.csv', 'rings.txt', 'sea.txt', 'way.txt']

Warm-up

A few short commands first, in the form of Chapter 0. The folder has the land of Indonesia as one shape, in metres. Draw it as a raster with cells of 3 km:

gdal vector rasterize /vsizip/indonesia.gpkg.zip land.tif --burn 1 --ot Byte --resolution 3000,3000 --extent -2700000,-1400000,2700000,900000 --overwrite

gdal raster edit land.tif --nodata none

gdal raster proximity land.tif away.tif --distance-units geo --overwrite

gdal raster color-map away.tif rings.png --color-map rings.txt --color-selection nearest --overwrite

Indonesia in sand colour in a sea with blue rings. Each ring is 100 kilometres wide and lighter than the one before. Around the islands they follow the coast, and far out they become round.

Command What it does
rasterize 1 is land, and 0 is everything else
edit --nodata none changes the file itself. rasterize marks the 0 as “no data”, and the next command would skip these cells
proximity gives each cell its distance to the nearest land, in metres
color-map a new colour every 100 km. nearest takes the nearest colour of the file and does not mix

Look before moving on. Near the coast, the rings have the shape of every bay. Farther out the details disappear and the rings become round. South of Java, there is no ring around Christmas Island. It belongs to Australia, and the file has the land of Indonesia only.

This chapter calculates the opposite: how far is it from the land to the sea?

1. All land, piece by piece

The land of the Earth comes from Natural Earth, in two files: one with the large pieces, and one with 2,795 small islands, which will matter later. -explodecollections gives each piece its own row:

ogr2ogr -overwrite land.gpkg /vsizip//vsicurl/https://naciscdn.org/naturalearth/10m/physical/ne_10m_land.zip -nln land -explodecollections -nlt POLYGON -sql "select scalerank from ne_10m_land"

ogr2ogr -update -append land.gpkg /vsizip//vsicurl/https://naciscdn.org/naturalearth/10m/physical/ne_10m_minor_islands.zip -nln land -explodecollections -nlt POLYGON -sql "select scalerank from ne_10m_minor_islands"

ogr2ogr -update -overwrite land.gpkg islands.csv -oo X_POSSIBLE_NAMES=lon -oo Y_POSSIBLE_NAMES=lat -oo AUTODETECT_TYPE=YES -a_srs EPSG:4326 -nln pin

ogr2ogr -f CSV /vsistdout/ land.gpkg -sql "select name, round(st_area(land.geom,1)/1e6) km2 from pin join land on st_intersects(land.geom,pin.geom) order by 2 desc limit 6"
name,km2
New Guinea,782049
Borneo,730588
Sumatra,427977
Sulawesi,170046
Java,126179
Timor,28762

The pieces have no names. The small file islands.csv has a name and one point inside for each of eighteen islands, and st_intersects finds the piece around the point. This method can name shapes, or select one out of thousands.

To work without a connection, download the two files, 3.6 MB together, and change the beginning of the addresses as in Chapter 1, section 9.

2. A map of distances

Take Borneo, and project it to metres, with the middle of the projection on the island:

ogr2ogr -overwrite borneo.gpkg land.gpkg -sql "select land.geom from pin join land on st_intersects(land.geom,pin.geom) where name='Borneo'" -nln borneo -t_srs "+proj=laea +lat_0=1 +lon_0=114 +datum=WGS84"

gdal pipeline read borneo.gpkg --input-layer borneo ! rasterize --burn 1 --init 0 --resolution 1000,1000 --extent "-600000,-600000,600000,700000" --ot Byte ! edit --nodata none ! proximity --target-values 0 --distance-units geo ! write far.tif --overwrite

gdal raster zonal-stats far.tif top.csv --zones borneo.gpkg --strategy raster --stat max --stat max_center_x --stat max_center_y --overwrite

ogr2ogr -f CSV /vsistdout/ top.csv -oo X_POSSIBLE_NAMES=max_center_x -oo Y_POSSIBLE_NAMES=max_center_y -oo AUTODETECT_TYPE=YES -s_srs "+proj=laea +lat_0=1 +lon_0=114 +datum=WGS84" -t_srs EPSG:4326 -lco GEOMETRY=AS_XY -sql "select max/1000 km from top"
X,Y,km
114.166190920447,0.425720428328747,328.24990625

The second line is the most important one of this chapter:

Step What it does
rasterize --burn 1 --init 0 draws the island into cells of 1 km: 1 is land, and 0 is sea
edit --nodata none makes the zeros ordinary numbers. The next step needs the sea
proximity --target-values 0 for each cell, the distance to the nearest cell with the value 0. On land, that is the distance to the sea
--distance-units geo in metres. Without it, the answer is in cells

The third line looks for the largest value inside the island. max_center_x and max_center_y are its place. The last line turns this place back into degrees, and gives the position of the maximum: 0.43 degrees north and 114.17 degrees east, about 328 km from the sea.

--strategy raster is necessary here. With the default strategy, GDAL 3.12.3 crashes when it has to find the place of a maximum in several areas (ledger L72), and section 5 will do this.

3. Three places on the coast at the same distance

The raster measures in cells of 1 km, from middle to middle. The true coast line is more exact. Measure from the point to the coast, and then find all places where the coast is almost as near:

ogr2ogr -update -overwrite borneo.gpkg top.csv -oo X_POSSIBLE_NAMES=max_center_x -oo Y_POSSIBLE_NAMES=max_center_y -oo AUTODETECT_TYPE=YES -a_srs "+proj=laea +lat_0=1 +lon_0=114 +datum=WGS84" -nln heart

ogr2ogr -update -overwrite borneo.gpkg borneo.gpkg -sql "select st_boundary(geom) geom from borneo" -nln coast

ogr2ogr -update -overwrite borneo.gpkg borneo.gpkg -sql "select st_linemerge(st_intersection(c.geom, st_buffer(h.geom, st_distance(c.geom,h.geom)+3000, 90))) geom from coast c, heart h" -nln touch -explodecollections -nlt LINESTRING

ogr2ogr -f CSV /vsistdout/ borneo.gpkg -sql "select round(st_distance(t.geom,h.geom)/1000,1) km, st_closestpoint(t.geom,h.geom) geom from touch t, heart h" -t_srs EPSG:4326 -lco GEOMETRY=AS_XY -nlt POINT
X,Y,km
111.383555535,1.35366445500006,326.3
112.974375847,3.14423248900005,328.5
116.728851759,-1.04404062299994,328.3

There are three places, and not one or two. This has a reason. Suppose only one place on the coast were the nearest. Then a step away from it would lead to a point farther inland. With two places, there would still be such a step, along the middle line between them. Only with three is there no such step. So the most inland point is the middle of the largest circle that fits into the island, and this circle touches the coast in at least three places.

Draw it. The colours are the distance, and the thin dark lines are places with the same distance, every 50 km:

gdal raster contour --interval 50000 --elevation-name m --output-layer iso far.tif iso.gpkg --overwrite

ogr2ogr -update -overwrite borneo.gpkg iso.gpkg iso

gdal pipeline read borneo.gpkg ! sql "select 5 v, st_buffer(geom,900) geom from iso where m>0 union all select 3, st_buffer(st_boundary(st_buffer(h.geom,st_distance(h.geom,c.geom),90)),1300) from heart h, coast c union all select 4, st_buffer(st_shortestline(h.geom,t.geom),1300) from heart h, touch t union all select 4, st_buffer(st_closestpoint(t.geom,h.geom),9000) from heart h, touch t union all select 3, st_buffer(geom,10000) from heart" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "4320,4680" --extent "-600000,-600000,600000,700000" ! edit --nodata none ! color-map --color-map ink.txt --add-alpha ! materialize ! resize --size "1440,1560" -r average ! write ink.tif --overwrite

gdal pipeline read far.tif ! resize --size "1440,1560" -r bilinear ! color-map --color-map far.txt ! write far_map.tif --overwrite

gdal raster blend far_map.tif ink.tif inland.png --overwrite

Borneo in colours from dark blue at the coast to pale yellow in the middle, with thin lines of equal distance. A large white circle fills the island. Three orange lines run from a white point in its middle to three orange dots on the coast, two in the north-west and one in the south-east.

Look before moving on. The lines of equal distance are the rings of Chapter 7, but on the land side. Near the coast they have the shape of every bay, and further inland they become simple. The bright lines between them are places with two nearest points on the coast.

Which towns are near this place? Calculate the nearest ones:

ogr2ogr -update -overwrite borneo.gpkg /vsizip//vsicurl/https://naciscdn.org/naturalearth/10m/cultural/ne_10m_populated_places_simple.zip -nln town -t_srs "+proj=laea +lat_0=1 +lon_0=114 +datum=WGS84" -spat 108 -5 120 8 -sql "select name, adm0name, pop_max from ne_10m_populated_places_simple"

ogr2ogr -f CSV /vsistdout/ borneo.gpkg -sql "select name, adm0name country, pop_max people, round(st_distance(t.geom,h.geom)/1000) km from town t, heart h order by 4 limit 4"
name,country,people,km
Palangkaraya,Indonesia,148289,293
Bintulu,Malaysia,151617,328
Sibu,Malaysia,203832,332
Samarinda,Indonesia,592228,348

The list of Natural Earth has only larger towns, and the nearest of them is almost 300 km away. The point lies in Indonesia, in the district of Murung Raya in Central Kalimantan, at about 1,500 m above the sea (ledger L76).

4. The shortest way to the sea

The raster contains how far the sea is, but not in which direction. st_shortestline gives the line itself. Set a point every 12 km, in rows where every second row is moved by half a step, and draw the shortest line from each of them to the coast:

ogr2ogr -update -overwrite borneo.gpkg borneo.gpkg -sql "with recursive c(i) as (select -49 union select i+1 from c where i<49), r(j) as (select -56 union select j+1 from r where j<65) select * from (select makepoint(12000*i+6000*mod(abs(j),2), 10392*j) geom from c, r) where st_within(geom, (select geom from borneo))" -nln start -nlt POINT

ogr2ogr -update -overwrite borneo.gpkg borneo.gpkg -sql "select st_length(geom)/1000 km, geom from (select st_shortestline(s.geom,c.geom) geom from start s, coast c)" -nln way -nlt LINESTRING

ogr2ogr -f CSV /vsistdout/ borneo.gpkg -sql "select count(*) lines, round(avg(km)) mean_km, round(max(km)) longest_km, round(100.0*avg(km<50)) percent_within_50_km from way"

gdal pipeline read borneo.gpkg ! sql "select cast(min(8,1+km/45) as integer) v, st_buffer(geom,700) geom from way order by km desc" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "4320,4680" --extent "-600000,-600000,600000,700000" ! edit --nodata none ! color-map --color-map way.txt ! materialize ! resize --size "1440,1560" -r average ! write way.png --overwrite
lines,mean_km,longest_km,percent_within_50_km
5864,104,325,33

Borneo drawn only by thousands of straight lines on black. They form fans, whose tips lie on the coast. The lines are dark blue near the coast and pale yellow at their inner ends. Dark gaps between the fans meet in the middle of the island.

Look before moving on. No outline is drawn, and the shape of the island is still visible. Each fan ends at a cape: many places share the same nearest point, because a cape lies farther out than the coast beside it. A bay is the nearest coast for only a few places.

The dark gaps are the lines where two nearest coasts are equally far. On both sides of them, the shortest lines go to different coasts. The gaps meet in the middle of the island, and one of the meeting points is the white dot of section 3.

5. Eighteen islands in one line

Now run the same calculation for all islands of the list. The lines hardly change. The projection must cover the whole archipelago, and the zones are now many shapes:

ogr2ogr -overwrite islands.gpkg land.gpkg -sql "select name, land.geom from pin join land on st_intersects(land.geom,pin.geom)" -nln island -t_srs "+proj=cea +lon_0=118 +datum=WGS84"

gdal pipeline read islands.gpkg --input-layer island ! rasterize --burn 1 --init 0 --resolution 1000,1000 --extent "-2900000,-1500000,4100000,1500000" --ot Byte ! edit --nodata none ! proximity --target-values 0 --distance-units geo ! write far_all.tif --overwrite

gdal raster zonal-stats far_all.tif tops.csv --zones islands.gpkg --include-field name --strategy raster --stat max --stat max_center_x --stat max_center_y --overwrite

ogr2ogr -update -overwrite islands.gpkg tops.csv -oo X_POSSIBLE_NAMES=max_center_x -oo Y_POSSIBLE_NAMES=max_center_y -oo AUTODETECT_TYPE=YES -a_srs "+proj=cea +lon_0=118 +datum=WGS84" -nln heart

ogr2ogr -update -overwrite islands.gpkg islands.gpkg -sql "select h.name, st_distance(h.geom, st_boundary(i.geom)) r, st_area(i.geom)/1e6 km2, h.geom from heart h join island i on i.name=h.name" -nln hub -nlt POINT

ogr2ogr -f CSV /vsistdout/ islands.gpkg -sql "select name, round(km2) km2, round(r/1000) km_to_sea, round(100*pi()*r*r/1e6/km2) percent_in_circle from hub order by r desc"
name,km2,km_to_sea,percent_in_circle
Borneo,730587,327,46
New Guinea,782048,290,34
Sumatra,427977,168,21
Sulawesi,170046,89,15
Java,126179,85,18
Timor,28762,47,24
Yos Sudarso,11632,46,57
Buru,8609,41,62
Sumbawa,14486,33,24
Seram,17347,32,18
Sumba,10832,31,28
Lombok,4664,30,61
Bali,5427,30,51
Flores,14311,29,18
Halmahera,18214,28,13
Bangka,11687,26,18
Belitung,4465,26,46
Madura,4420,18,24

--include-field name copies the names into the result. Some rows of the table may be unexpected:

  • New Guinea is larger than Borneo, but its most inland point is nearer to the sea. A long island has no place far from the sea.
  • Sulawesi is a third larger than Java, and its most inland point is hardly farther from the sea. It consists of four narrow peninsulas.
  • The last column is the part of the island that lies inside its largest circle. For a round island this would be 100 percent. Sulawesi reaches 15, and only Halmahera, which has a similar shape, has less.

The projection cea is not exact for distances. Near the equator the error is small, and at 10 degrees of latitude it is about 1.5 percent (ledger L73).

gdal pipeline read islands.gpkg ! sql "select 3 v, st_buffer(st_boundary(st_buffer(geom,r,60)),3200) geom from hub union all select 4, st_buffer(geom,9000+r/40) from hub" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "7200,3084" --extent "-2900000,-1500000,4100000,1500000" ! edit --nodata none ! color-map --color-map ink.txt --add-alpha ! materialize ! resize --size "1800,771" -r average ! write ink.tif --overwrite

gdal pipeline read far_all.tif ! resize --size "1800,771" -r average ! color-map --color-map far.txt ! write far_map.tif --overwrite

gdal raster blend far_map.tif ink.tif islands.png --overwrite

The islands from Sumatra to New Guinea in dark blue, with a bright middle in Borneo and a less bright one in New Guinea. A white circle with an orange point stands in each of eighteen islands, the largest one in Borneo. The circles of Sulawesi and Java are small and almost equal.

6. The point in the ocean farthest from land

Now the opposite question: which place in the sea is farthest from any land? It lies in the South Pacific, and is called Point Nemo, after the captain in a novel by Jules Verne. The US ocean agency NOAA gives its coordinates: 48°52.6′ south and 123°23.6′ west, about 2,688 km from the nearest land (ledger L74). So the method of this chapter can be checked against a known answer.

One thing is different: the size. Over thousands of kilometres, a flat map cannot keep all distances true. But an azimuthal equidistant projection (aeqd) keeps those from its middle to everywhere. So work in two steps: find the place roughly, and then put the middle of the projection there. First roughly, with cells of 10 km:

ogr2ogr -overwrite near.gpkg land.gpkg -sql "select geom from land where st_maxy(geom)<35 and (st_minx(geom)>130 or st_maxx(geom)<-60 or st_miny(geom)<-60)" -nln near -t_srs "+proj=laea +lat_0=-45 +lon_0=-120 +datum=WGS84"

ogr2ogr -overwrite box.gpkg land.gpkg -sql "select buildmbr(-2500000,-2500000,2500000,2500000) geom" -nln box -a_srs "+proj=laea +lat_0=-45 +lon_0=-120 +datum=WGS84"

gdal pipeline read near.gpkg --input-layer near ! rasterize --burn 1 --init 0 --all-touched --resolution 10000,10000 --extent "-6000000,-6000000,6000000,6000000" --ot Byte ! edit --nodata none ! proximity --target-values 1 --distance-units geo ! write sea.tif --overwrite

gdal raster zonal-stats sea.tif nemo.csv --zones box.gpkg --strategy raster --stat max --stat max_center_x --stat max_center_y --overwrite

ogr2ogr -f CSV /vsistdout/ nemo.csv -oo X_POSSIBLE_NAMES=max_center_x -oo Y_POSSIBLE_NAMES=max_center_y -oo AUTODETECT_TYPE=YES -s_srs "+proj=laea +lat_0=-45 +lon_0=-120 +datum=WGS84" -t_srs EPSG:4326 -lco GEOMETRY=AS_XY -sql "select max/1000 km from nemo"
X,Y,km
-124.570858099163,-48.9175814809697,2681

Three details changed. --target-values 1 now gives the distance to the nearest land. --all-touched draws every cell that an island touches, because many islands are smaller than a cell and would be lost. And the zone is not an island, but a box in the middle of the raster. Near the edge, land outside the raster is missing, and the distances there are too large.

The first answer is near 49 degrees south and 124 degrees west. Now put the middle of an equidistant projection there, and calculate again with cells of 2 km:

ogr2ogr -overwrite near.gpkg land.gpkg -sql "select geom from land where st_maxy(geom)<35 and (st_minx(geom)>130 or st_maxx(geom)<-60 or st_miny(geom)<-60)" -nln near -t_srs "+proj=aeqd +lat_0=-48.9 +lon_0=-124 +datum=WGS84"

ogr2ogr -overwrite box.gpkg land.gpkg -sql "select buildmbr(-300000,-300000,300000,300000) geom" -nln box -a_srs "+proj=aeqd +lat_0=-48.9 +lon_0=-124 +datum=WGS84"

gdal pipeline read near.gpkg --input-layer near ! rasterize --burn 1 --init 0 --all-touched --resolution 2000,2000 --extent "-6000000,-6000000,6000000,6000000" --ot Byte ! edit --nodata none ! proximity --target-values 1 --distance-units geo ! write sea.tif --overwrite

gdal raster zonal-stats sea.tif nemo.csv --zones box.gpkg --strategy raster --stat max --stat max_center_x --stat max_center_y --overwrite

ogr2ogr -f CSV /vsistdout/ nemo.csv -oo X_POSSIBLE_NAMES=max_center_x -oo Y_POSSIBLE_NAMES=max_center_y -oo AUTODETECT_TYPE=YES -s_srs "+proj=aeqd +lat_0=-48.9 +lon_0=-124 +datum=WGS84" -t_srs EPSG:4326 -lco GEOMETRY=AS_XY -sql "select max/1000 km from nemo"
X,Y,km
-123.439495723861,-49.0155373816418,2704

Is it right? Almost, but the difference is too large. Our point lies at 49.02 degrees south, and NOAA’s at 48.88. The difference is about 16 km, much more than a cell. Our distance is also too large, 2,704 instead of 2,688 km.

NOAA names the three nearest pieces of land: Ducie Island, Motu Nui near Easter Island, and Maher Island in Antarctica. Is Maher Island on our map? It lies at 72°58′ south and 126°22′ west (ledger L74):

ogr2ogr -f CSV /vsistdout/ land.gpkg -sql "select round(min(st_length(st_shortestline(setsrid(makepoint(-126.37,-72.97),4326), geom),1))/1000,1) km_to_nearest_land_on_our_map from land where st_maxy(geom)<-60"
km_to_nearest_land_on_our_map
34.3

It is missing: the nearest land on our map is 34 km away from its place. So add it, as a tiny round island made by hand, and run the same lines once more:

ogr2ogr -update -append land.gpkg land.gpkg -sql "select 0 scalerank, st_buffer(setsrid(makepoint(-126.37,-72.97),4326),0.01) geom" -nln land

ogr2ogr -overwrite near.gpkg land.gpkg -sql "select geom from land where st_maxy(geom)<35 and (st_minx(geom)>130 or st_maxx(geom)<-60 or st_miny(geom)<-60)" -nln near -t_srs "+proj=aeqd +lat_0=-48.9 +lon_0=-124 +datum=WGS84"

gdal pipeline read near.gpkg --input-layer near ! rasterize --burn 1 --init 0 --all-touched --resolution 2000,2000 --extent "-6000000,-6000000,6000000,6000000" --ot Byte ! edit --nodata none ! proximity --target-values 1 --distance-units geo ! write sea.tif --overwrite

gdal raster zonal-stats sea.tif nemo.csv --zones box.gpkg --strategy raster --stat max --stat max_center_x --stat max_center_y --overwrite

ogr2ogr -f CSV /vsistdout/ nemo.csv -oo X_POSSIBLE_NAMES=max_center_x -oo Y_POSSIBLE_NAMES=max_center_y -oo AUTODETECT_TYPE=YES -s_srs "+proj=aeqd +lat_0=-48.9 +lon_0=-124 +datum=WGS84" -t_srs EPSG:4326 -lco GEOMETRY=AS_XY -sql "select max/1000 km from nemo"

ogr2ogr -update -overwrite near.gpkg nemo.csv -oo X_POSSIBLE_NAMES=max_center_x -oo Y_POSSIBLE_NAMES=max_center_y -oo AUTODETECT_TYPE=YES -a_srs "+proj=aeqd +lat_0=-48.9 +lon_0=-124 +datum=WGS84" -nln nemo

ogr2ogr -f CSV /vsistdout/ near.gpkg -sql "select round(st_length(st_shortestline(nemo.geom,setsrid(makepoint(0,0),st_srid(nemo.geom))))/1000) km_from_the_middle, (select count(*) from near where st_distance(near.geom,nemo.geom)<nemo.max+3000) pieces_of_land_on_the_circle from nemo"
X,Y,km
-123.386580092119,-48.8713913163564,2688.86075
km_from_the_middle,pieces_of_land_on_the_circle
45,3

Look before moving on. With one more island, which is tiny on this map, the point moved by 16 km, and now lies within a kilometre of NOAA’s. The distance is also right to about a kilometre. And the circle touches three pieces of land.

This is an important result of the chapter: the farthest place depends on the smallest island. A map that leaves out a small island moves the maximum. The result for Borneo in section 2 has the same weakness. The coast of Natural Earth is simplified, so treat that result as right to a few kilometres.

ogr2ogr -update -overwrite near.gpkg near.gpkg -sql "select st_shortestline(nemo.geom,near.geom) geom, nemo.max r from near, nemo where st_distance(near.geom,nemo.geom)<nemo.max+3000" -nln ray -nlt LINESTRING

gdal raster contour --interval 500000 --elevation-name m --output-layer iso sea.tif iso.gpkg --overwrite

ogr2ogr -update -overwrite near.gpkg iso.gpkg iso

gdal pipeline read near.gpkg ! sql "select 5 v, st_buffer(geom,4500) geom from iso where m>0 union all select 7, st_buffer(geom,5000) from near union all select 3, st_buffer(st_boundary(st_buffer(geom,max,90)),8000) from nemo union all select 4, st_buffer(geom,8000) from ray union all select 4, st_buffer(st_endpoint(geom),50000) from ray union all select 3, st_buffer(geom,55000) from nemo" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "4200,4200" --extent "-3500000,-3500000,3500000,3500000" ! edit --nodata none ! color-map --color-map ink.txt --add-alpha ! materialize ! resize --size "1400,1400" -r average ! write ink.tif --overwrite

gdal pipeline read sea.tif ! clip --bbox "-3500000,-3500000,3500000,3500000" ! resize --size "1400,1400" -r bilinear ! color-map --color-map sea.txt ! write far_map.tif --overwrite

gdal raster blend far_map.tif ink.tif nemo.png --overwrite

The South Pacific in colours from dark blue near land to pale yellow far from it. A white point lies in the middle of a huge white circle. Three orange lines reach from it to the edge of the circle: to a tiny island in the north, to Easter Island in the north-east, and to the coast of Antarctica in the south. South America is at the right edge, and many tiny islands lie in the upper left.

7. Which airport is the nearest?

The question here is not how far the nearest one is, but which one it is. Every place in Indonesia has a nearest airport, and all places with the same nearest one form an area. Such a division is called a Voronoi diagram, and SQL has a function for it.

airports.csv has 243 airports of Indonesia, those that are in use and have an IATA code, such as CGK. They come from OurAirports, a list made by volunteers, in the public domain (ledger L75). The file was made from the full list with this line, if you want a newer one or another country:

ogr2ogr -f CSV airports.csv "CSV:/vsicurl/https://davidmegginson.github.io/ourairports-data/airports.csv" -dialect SQLite -sql "select iata_code iata, name, municipality town, type, round(cast(longitude_deg as real),5) lon, round(cast(latitude_deg as real),5) lat from airports where iso_country='ID' and iata_code<>'' and type in ('large_airport','medium_airport','small_airport') order by 1"

(The list also has a column for airports with scheduled flights. We did not use this column. For some airports its value looked doubtful, and an IATA code is easier to check.)

ogr2ogr -overwrite turf.gpkg airports.csv -oo X_POSSIBLE_NAMES=lon -oo Y_POSSIBLE_NAMES=lat -oo AUTODETECT_TYPE=YES -s_srs EPSG:4326 -t_srs "+proj=cea +lon_0=118 +datum=WGS84" -nln airport

ogr2ogr -update -overwrite turf.gpkg indonesia.gpkg.zip indonesia

ogr2ogr -update -overwrite turf.gpkg turf.gpkg -sql "select st_voronojdiagram(st_collect(geom)) geom from airport" -nln cell -explodecollections -nlt POLYGON

ogr2ogr -update -overwrite turf.gpkg turf.gpkg -sql "select iata, name, town, st_intersection(c.geom,i.geom) geom from cell c join airport a on st_intersects(c.geom,a.geom), indonesia i" -nln turf -nlt PROMOTE_TO_MULTI

ogr2ogr -f CSV /vsistdout/ turf.gpkg -sql "select iata, town, round(st_area(geom)/1e6) km2 from turf order by 3 desc limit 5"

ogr2ogr -f CSV /vsistdout/ turf.gpkg -sql "select count(*) airports, round(sum(st_area(geom))/1e6) km2_of_all_territories, (select round(st_area(geom)/1e6) from indonesia) km2_of_indonesia from turf"
iata,town,km2
PSU,Putussibau-Borneo Island,30813
SQG,Sintang,29363
LPU,Long Apung-Borneo Island,27951
DJB,Jambi,27395
RGT,Rengat-Sumatra Island,27223
airports,km2_of_all_territories,km2_of_indonesia
243,1890314,1890314
Part Meaning
st_collect(geom) all airports as one shape with many points, because the function accepts only one shape
st_voronojdiagram divides the plane. The name is really written with a j in SpatiaLite
-explodecollections one row for each cell
join ... on st_intersects(c.geom,a.geom) the cells have lost their names. Each one contains exactly one airport, and gets its name back
st_intersection(c.geom,i.geom) keeps the land. indonesia.gpkg.zip is the land of Chapter 7 in one shape

Is it right? The areas of all airports together are as large as the country. No land was lost, and none was counted twice.

Three of the five largest areas lie in the inner part of Borneo, around the point of section 2. A large area does not mean a busy airport. It means an airport without near neighbours.

8. Two ways to the same border

This section compares the raster method with the method of section 7. Calculate the distance to the nearest airport as a raster, and draw the borders of the areas on top:

gdal pipeline read turf.gpkg --input-layer airport ! rasterize --burn 1 --init 0 --resolution 1000,1000 --extent "-2650000,-1300000,2650000,900000" --ot Byte ! edit --nodata none ! proximity --target-values 1 --distance-units geo ! write hop.tif --overwrite

gdal pipeline read turf.gpkg ! sql "select 1 v, st_difference(buildmbr(-2700000,-1400000,2700000,1000000), geom) geom from indonesia union all select 5, st_buffer(st_boundary(geom),1100) from turf union all select 3, st_buffer(geom,5200) from airport" ! edit --crs none ! rasterize --attribute-name v --init 0 --ot Byte --size "7200,2988" --extent "-2650000,-1300000,2650000,900000" ! edit --nodata none ! color-map --color-map ink.txt --add-alpha ! materialize ! resize --size "1800,747" -r average ! write ink.tif --overwrite

gdal pipeline read hop.tif ! resize --size "1800,747" -r bilinear ! color-map --color-map hop.txt ! write far_map.tif --overwrite

gdal raster blend far_map.tif ink.tif turf.png --overwrite

Indonesia as a mosaic of bright colours. A white dot marks each airport, and around it the land is dark red. With distance it turns orange and then pale yellow. Thin dark lines separate the areas, and they run exactly along the brightest places.

Look before moving on. The colours come from a raster that does not use the areas. The lines come from geometry that does not use the raster. And each line runs along the brightest places. This must be so: on a border, two airports are equally far, and on both sides one of them is nearer.

A border between points is always straight, and between coasts it can bend, as in section 4. But the principle is the same.

Which place in Indonesia is farthest from all these airports? The line for this is the one from section 2:

gdal raster zonal-stats hop.tif lost.csv --zones indonesia.gpkg.zip --strategy raster --stat max --stat max_center_x --stat max_center_y --stat mean --overwrite

ogr2ogr -f CSV /vsistdout/ lost.csv -oo X_POSSIBLE_NAMES=max_center_x -oo Y_POSSIBLE_NAMES=max_center_y -oo AUTODETECT_TYPE=YES -s_srs "+proj=cea +lon_0=118 +datum=WGS84" -t_srs EPSG:4326 -lco GEOMETRY=AS_XY -sql "select max/1000 km from lost"

ogr2ogr -update -overwrite turf.gpkg lost.csv -oo X_POSSIBLE_NAMES=max_center_x -oo Y_POSSIBLE_NAMES=max_center_y -oo AUTODETECT_TYPE=YES -a_srs "+proj=cea +lon_0=118 +datum=WGS84" -nln lost

ogr2ogr -f CSV /vsistdout/ turf.gpkg -sql "select iata, name, town, round(st_distance(a.geom,l.geom)/1000) km, (select round(mean/1000) from lost) mean_km_of_all_places from airport a, lost l order by 4 limit 3"
X,Y,km
129.520893518833,-6.72089204585506,237.023203125
iata,name,town,km,mean_km_of_all_places
SXK,Mathilda Batlayeri Airport,Saumlaki-Yamdena Island,237,55
JIO,Jos Orno Imsula Airport,Tiakur,238,55
NDA,Bandanaira Airport,Bandanaira,246,55

It is a small island in the Banda Sea, in the district of Maluku Barat Daya. The nearest airport is 237 km away, and the second one is hardly farther. From the average place in Indonesia, it is 55 km to an airport with a code, in a straight line.

Try it yourself

  • Your own island. Add a row to islands.csv, with a point that lies on the island. For a country without a coast, the same lines find the place that is farthest from the border.
  • Lakes as water. The lines treat Lake Toba as land. Remove the lakes from Sumatra with st_difference, and check how far the point moves.
  • Finer cells. Change 1000 to 250 in section 2. The file becomes 16 times as large. How far does the point move?
  • Other points. Replace the airports by hospitals, schools or your own list. Which place is farthest from the next one?
  • The farthest place from the sea in Asia. Which place is it? You need another projection, and the two steps of section 6.

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} -sql "{sql}"'))))

# The most inland point of Borneo: the raster and the true coast line must agree to two cells
raster = float(rows("select max a from heart", "borneo.gpkg")[0]["a"])
vector = float(rows("select st_distance(h.geom,c.geom) a from heart h, coast c", "borneo.gpkg")[0]["a"])
assert abs(raster - vector) < 3000, "raster and coast line should give about the same distance"
assert rows("select count(*) n from touch", "borneo.gpkg")[0]["n"] == "3", "the circle should touch the coast in three places"

# Point Nemo against NOAA: 48 degrees 52.6 minutes south, 123 degrees 23.6 minutes west, 2,688 km
import math
got = oneline.run("""ogr2ogr -f CSV /vsistdout/ near.gpkg nemo -t_srs EPSG:4326 -lco GEOMETRY=AS_XY""").splitlines()[1].split(",")
lon, lat, km = float(got[0]), float(got[1]), float(rows("select max/1000 a from nemo", "near.gpkg")[0]["a"])
off = math.hypot((lon + 123 + 23.6 / 60) * 111.2 * math.cos(math.radians(lat)), (lat + 48 + 52.6 / 60) * 111.2)
assert off < 3 and abs(km - 2688) < 2, f"Point Nemo should be near NOAA's place, but is {off:.1f} km away"

parts, whole = (float(rows(q, "turf.gpkg")[0]["a"]) for q in ("select sum(st_area(geom)) a from turf", "select st_area(geom) a from indonesia"))
assert abs(parts / whole - 1) < 1e-6, "the territories should cover the country exactly"

pictures = ("inland.png", "way.png", "islands.png", "nemo.png", "turf.png")
assert all((WORK / f).stat().st_size > 10_000 for f in pictures)
print(f"checkpoint passed: Borneo {vector / 1000:.1f} km from the sea; Point Nemo {off:.1f} km from NOAA's place, at {km:,.1f} km; territories cover the country")
print(f"time since the first cell: {time.perf_counter() - T0:.0f} s")
checkpoint passed: Borneo 326.3 km from the sea; Point Nemo 0.8 km from NOAA's place, at 2,688.9 km; territories cover the country
time since the first cell: 140 s

Troubleshooting

Symptom Cause Fix
zonal-stats stops after a few areas, or the shell reports a crash max_center_x with the default strategy, in GDAL 3.12.3 (ledger L72) --strategy raster
The distance is small numbers such as 328 It is in cells --distance-units geo
The whole map has the same colour proximity found no target edit --nodata none before it, and the right --target-values
The largest distance is at the edge of the raster Land or sea beyond the edge is missing A larger --extent, and a zone in the middle
Argument '-t_srs' not allowed with '-a_srs' -a_srs only records the system and does not convert the coordinates -s_srs together with -t_srs
no such function: st_voronoidiagram SpatiaLite writes it with a j st_voronojdiagram

What comes next

In this chapter, a raster was made from shapes, and it contained distances. Most rasters contain something else, for example the height of the land. Chapter 9: Relief drawn with profile lines goes in the other direction, from a raster to shapes, and draws the heights of a whole island with a small number of lines.

Land and towns: Natural Earth, in the public domain. Airports: OurAirports, in the public domain, read on 3 December 2026. Land of Indonesia: Badan Pusat Statistik (BPS), by way of OCHA, CC BY-IGO, simplified and joined, as in Chapter 7.