GeoFrame deck.gl map on real data

Copy Markdown View Source
Mix.install(
  [
    {:geoframe, path: Path.join(__DIR__, "..")},
    {:kino, "~> 0.19"},
    {:req, "~> 0.5"}
  ]
)

Binary maps with deck.gl

GeoFrame.Kino.deck/2 ships geometry to the browser as typed-array buffers (no GeoJSON) and draws it with deck.gl, so a million points stay interactive. deck.gl and the Carto basemap load from the internet in your browser.

The examples use Natural Earth vector data (public domain), downloaded on first run into the system temp directory.

base = "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson"

fetch = fn name ->
  path = Path.join(System.tmp_dir!(), name)

  unless File.exists?(path) do
    Req.get!("#{base}/#{name}", into: File.stream!(path)) |> then(& &1.status) |> then(&(200 = &1))
  end

  path
end

World countries

Read the 110m countries file and color each country by population with the viridis ramp. A handful of countries hold most of the people, so the ramp runs over the base-10 logarithm of the population; otherwise China and India are yellow and everything else is the same dark purple. Hover for the name, population and GDP.

countries =
  fetch.("ne_110m_admin_0_countries.geojson")
  |> GeoFrame.read_file!()
  |> GeoFrame.GeoDataFrame.select(["NAME", "ADM0_A3", "CONTINENT", "POP_EST", "GDP_MD"])
  |> GeoFrame.GeoDataFrame.mutate_with(fn df ->
    [LOG_POP: Explorer.Series.log(df["POP_EST"], 10)]
  end)

GeoFrame.Kino.deck(countries,
  color: {"LOG_POP", :viridis},
  opacity: 0.8,
  tooltip: ["NAME", "POP_EST", "GDP_MD"]
)

A column color comes with a legend card in the bottom-right corner (a gradient bar with ticks here, swatches for :categorical; pass legend: false to hide it), and metric and imperial scale bars sit in the bottom-left corner (scale: false hides them).

Population alone mostly maps country size. Project to an equal-area CRS (EPSG:6933), compute the area in km² and color by the logarithm of the people per km² instead; the widget reprojects back to longitude and latitude by itself.

density =
  countries
  |> GeoFrame.GeoDataFrame.to_crs("EPSG:6933")
  |> then(fn gdf ->
    area_km2 = gdf |> GeoFrame.GeoDataFrame.area() |> Explorer.Series.divide(1_000_000)
    GeoFrame.GeoDataFrame.put(gdf, "AREA_KM2", area_km2)
  end)
  |> GeoFrame.GeoDataFrame.mutate_with(fn df ->
    density = Explorer.Series.divide(df["POP_EST"], df["AREA_KM2"])
    [DENSITY: density, LOG_DENSITY: Explorer.Series.log(density, 10)]
  end)

GeoFrame.Kino.deck(density,
  color: {"LOG_DENSITY", :viridis},
  tooltip: ["NAME", "POP_EST", "DENSITY"]
)

Cities

The 10m populated places as points, cities above one million people only. The circle area follows the largest population estimate (:radius takes a numeric column and scales it to 2-20 px), and the color follows its logarithm. Hover for name, country and population.

cities =
  fetch.("ne_10m_populated_places_simple.geojson")
  |> GeoFrame.read_file!()
  |> GeoFrame.GeoDataFrame.select(["name", "adm0name", "pop_max", "megacity"])

big_cities =
  cities
  |> GeoFrame.GeoDataFrame.filter_with(&Explorer.Series.greater(&1["pop_max"], 1_000_000))
  |> GeoFrame.GeoDataFrame.mutate_with(fn df ->
    [LOG_POP: Explorer.Series.log(df["pop_max"], 10)]
  end)

GeoFrame.Kino.deck(big_cities,
  color: {"LOG_POP", :viridis},
  radius: "pop_max",
  opacity: 0.7,
  tooltip: ["name", "adm0name", "pop_max"]
)

Rivers

The 50m river centerlines are lines. Color them by the Natural Earth scalerank (smaller is a more important river, so purple rivers are the major ones) and draw them 2 px wide; :width also accepts a numeric column, scaled to 1-8 px.

rivers = fetch.("ne_50m_rivers_lake_centerlines.geojson") |> GeoFrame.read_file!()

GeoFrame.Kino.deck(rivers, color: {"scalerank", :viridis}, width: 2, tooltip: ["name", "scalerank"])

Click popups and several layers

popup: opens a closable card with the chosen attributes where you click a feature, like explore(popup=True) in GeoPandas; the hover tooltip keeps working next to it. Values are shown as plain text, never as HTML. To draw several frames on one map, pass a list: each entry is a frame or {frame, options} with its own color, size, legend, tooltip and popup, and a layer control in the top-left corner toggles each layer (and its legend). Click a country, then a city, and untick "Cities" to hide them. :max_features and :max_vertices are totals over the layers.

GeoFrame.Kino.deck(
  [
    {countries,
     name: "Countries",
     color: {"LOG_POP", :viridis},
     opacity: 0.6,
     popup: ["NAME", "CONTINENT", "POP_EST"]},
    {big_cities,
     name: "Cities",
     color: {200, 30, 30},
     radius: 4,
     tooltip: ["name"],
     popup: ["name", "adm0name", "pop_max"]}
  ],
  height: 520
)

Cities per country

A spatial join answers "which country is each city in?". Keep the country name and code, join every city to the country polygon that contains it, then count the cities per country and color the countries by the logarithm of that count; countries without a city stay gray.

alias Explorer.DataFrame, as: DF

country_keys = GeoFrame.GeoDataFrame.select(countries, ["ADM0_A3"])

located = GeoFrame.sjoin(cities, country_keys, how: :inner, predicate: :within)

counts =
  located
  |> GeoFrame.GeoDataFrame.data()
  |> DF.group_by("ADM0_A3")
  |> DF.summarise_with(&[N_CITIES: Explorer.Series.count(&1["name"])])

by_country =
  countries
  |> GeoFrame.GeoDataFrame.join(counts, on: "ADM0_A3", how: :left)
  |> GeoFrame.GeoDataFrame.mutate_with(fn df ->
    [LOG_CITIES: Explorer.Series.log(df["N_CITIES"], 10)]
  end)

GeoFrame.Kino.deck(by_country, color: {"LOG_CITIES", :viridis}, tooltip: ["NAME", "N_CITIES"])

Smart Cells

With geoframe installed, Livebook's Smart menu offers two cells that write the code for you:

The cells generate plain Elixir, which Convert to Code cell keeps. Point Read spatial file at the cities file the notebook downloaded (Path.join(System.tmp_dir!(), "ne_10m_populated_places_simple.geojson")), and in Spatial join pick cities on the left and countries on the right with the within predicate. This is what they write, and it runs headlessly:

path = Path.join(System.tmp_dir!(), "ne_10m_populated_places_simple.geojson")

places = GeoFrame.read_file!(path)
joined = GeoFrame.sjoin(places, countries, how: :inner, predicate: :within)

GeoFrame.Kino.deck(joined, radius: 3, tooltip: ["name", "NAME"])

Scaling: one million points (optional)

Random points over South Florida, reprojected from Web Mercator to show that the widget converts to longitude/latitude first. Color by a categorical column and size by a number.

n = 1_000_000
lon = for _ <- 1..n, do: -80.9 + :rand.uniform() * 1.1
lat = for _ <- 1..n, do: 25.2 + :rand.uniform() * 1.0

points =
  GeoFrame.GeoSeries.from_xy(lon, lat, crs: "EPSG:4326")
  |> GeoFrame.GeoSeries.to_crs(3857)

frame =
  GeoFrame.GeoDataFrame.new(
    Explorer.DataFrame.new(
      zone: Enum.map(1..n, &Enum.at(["a", "b", "c"], rem(&1, 3))),
      size: Enum.map(1..n, fn _ -> :rand.uniform() end)
    ),
    points
  )

GeoFrame.Kino.deck(frame,
  color: {:zone, :categorical},
  radius: :size,
  opacity: 0.6,
  tooltip: [:zone, :size]
)