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 sysimport timefrom pathlib import Path# The repository root, whether the notebook runs from en/, id/ or the root itselfROOT = Path.cwd() if (Path.cwd() /"tutorial.yml").exists() else Path.cwd().parentsys.path.insert(0, str(ROOT /"src"))import onelineT0 = 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()))
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:
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 pinogr2ogr-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 twofiles, 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:
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:
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 --overwriteogr2ogr-update-overwrite borneo.gpkg iso.gpkg isogdal 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 --overwritegdal pipeline read far.tif ! resize --size"1440,1560"-r bilinear ! color-map --color-map far.txt ! write far_map.tif --overwritegdal raster blend far_map.tif ink.tif inland.png --overwrite
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"
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 POINTogr2ogr-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 LINESTRINGogr2ogr-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
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 --overwritegdal 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 --overwriteogr2ogr-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 heartogr2ogr-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 POINTogr2ogr-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"
--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).
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 --overwritegdal raster zonal-stats sea.tif nemo.csv --zones box.gpkg --strategy raster --stat max --stat max_center_x --stat max_center_y --overwriteogr2ogr-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 --overwritegdal raster zonal-stats sea.tif nemo.csv --zones box.gpkg --strategy raster --stat max --stat max_center_x --stat max_center_y --overwriteogr2ogr-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 landogr2ogr-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 --overwritegdal raster zonal-stats sea.tif nemo.csv --zones box.gpkg --strategy raster --stat max --stat max_center_x --stat max_center_y --overwriteogr2ogr-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 nemoogr2ogr-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"
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 LINESTRINGgdal raster contour --interval 500000 --elevation-name m --output-layer iso sea.tif iso.gpkg --overwriteogr2ogr-update-overwrite near.gpkg iso.gpkg isogdal 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 --overwritegdal 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 --overwritegdal raster blend far_map.tif ink.tif nemo.png --overwrite
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 airportogr2ogr-update-overwrite turf.gpkg indonesia.gpkg.zip indonesiaogr2ogr-update-overwrite turf.gpkg turf.gpkg -sql"select st_voronojdiagram(st_collect(geom)) geom from airport"-nln cell -explodecollections-nlt POLYGONogr2ogr-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_MULTIogr2ogr-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"
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:
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 --overwriteogr2ogr-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 lostogr2ogr-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"
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 csvimport iodef rows(sql, dataset):"""The rows of a query, as dictionaries."""returnlist(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 cellsraster =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"])assertabs(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 kmimport mathgot = 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 <3andabs(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"))assertabs(parts / whole -1) <1e-6, "the territories should cover the country exactly"pictures = ("inland.png", "way.png", "islands.png", "nemo.png", "turf.png")assertall((WORK / f).stat().st_size >10_000for 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.