Skip to content

basemap

basemap #

basemap — a muted street map under a chart of places.

  1. Frame. The chart is framed around the places in Web Mercator metres, stray fixes aside, and widened to a minimum size.
  2. Tile. OpenStreetMap tiles at the zoom the chart's width needs are fetched once each (osm_tile is memoized), stitched and muted under the data.
  3. Project. The returned function places any latitude and longitude on the chart.

LEAST_HALF_METERS = 40.0 module-attribute #

Half the smallest stretch of ground a basemap shows.

Projection = Callable[[np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray]] #

(latitude, longitude) in degrees to (x, y) on the chart.

basemap(axes, locations) #

Frame axes around locations over a muted OpenStreetMap street map.

to_map = guidance.basemap(figure.axes, photographed)
figure.axes.scatter(*to_map(latitudes, longitudes))

Parameters:

Name Type Description Default
axes Axes

The chart to draw on; it takes equal aspect and loses its ticks.

required
locations Array[Location]

The places to frame; the outermost 2% are left out of the frame.

required

Returns:

Type Description
Projection

The projection from latitude and longitude onto the chart.

Raises:

Type Description
ValueError

If locations holds no place.

URLError

If a tile cannot be fetched.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/guidance/basemap.py
def basemap(
    axes: Axes,
    locations: cg.Array[cg.Location],
) -> Projection:
    """Frame ``axes`` around ``locations`` over a muted OpenStreetMap street map.

    ```python
    to_map = guidance.basemap(figure.axes, photographed)
    figure.axes.scatter(*to_map(latitudes, longitudes))
    ```

    Args:
        axes: The chart to draw on; it takes equal aspect and loses its ticks.
        locations: The places to frame; the outermost 2% are left out of the frame.

    Returns:
        The projection from latitude and longitude onto the chart.

    Raises:
        ValueError: If ``locations`` holds no place.
        urllib.error.URLError: If a tile cannot be fetched.
    """
    present = [where for where in locations if not cg.is_missing(where)]
    if not present:
        raise ValueError("a basemap needs at least one place to frame")
    x, y = mercator(
        np.array([where.latitude for where in present]),
        np.array([where.longitude for where in present]),
    )
    stretch = 1.0 / math.cos(math.radians(float(np.median([w.latitude for w in present]))))
    (x_low, x_high), (y_low, y_high) = np.percentile(x, [2, 98]), np.percentile(y, [2, 98])
    half = max((x_high - x_low) * 0.65, (y_high - y_low) * 0.65, LEAST_HALF_METERS * stretch)
    west, east = (x_low + x_high) / 2 - half, (x_low + x_high) / 2 + half
    south, north = (y_low + y_high) / 2 - half, (y_low + y_high) / 2 + half

    world = 2 * math.pi * EARTH_RADIUS_METERS
    tiles_across = axes.get_window_extent().width / TILE_SIZE
    zoom = min(MAX_ZOOM, max(0, math.ceil(math.log2(tiles_across * world / (east - west)))))
    axes.imshow(
        _streets(zoom, west, south, east, north),
        extent=(west, east, south, north),
        interpolation="lanczos",
        zorder=0,
    )
    _scale_bar(axes, half / stretch, stretch)
    axes.text(
        0.99,
        0.01,
        "© OpenStreetMap contributors",
        transform=axes.transAxes,
        ha="right",
        va="bottom",
        fontsize=11,
        color=INK,
        backgroundcolor=(1, 1, 1, 0.7),
    )
    axes.set_xlim(west, east)
    axes.set_ylim(south, north)
    axes.set_aspect("equal")
    axes.set_axis_off()
    return mercator

mercator(latitude, longitude) #

Latitude and longitude, in degrees, as Web Mercator metres.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/guidance/basemap.py
def mercator(
    latitude: np.ndarray,
    longitude: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
    """Latitude and longitude, in degrees, as Web Mercator metres."""
    x = EARTH_RADIUS_METERS * np.radians(np.asarray(longitude, dtype=np.float64))
    y = EARTH_RADIUS_METERS * np.log(
        np.tan(np.pi / 4 + np.radians(np.asarray(latitude, dtype=np.float64)) / 2)
    )
    return x, y

osm_tile(zoom, x, y) #

One OpenStreetMap tile, fetched once and kept.

Raises:

Type Description
URLError

If the tile server cannot be reached or refuses.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/guidance/basemap.py
@cg.pure_function("guidance.osm_tile/1")
def osm_tile(
    zoom: int,
    x: int,
    y: int,
) -> cg.Image:
    """One OpenStreetMap tile, fetched once and kept.

    Raises:
        urllib.error.URLError: If the tile server cannot be reached or refuses.
    """
    request = urllib.request.Request(
        TILE_URL.format(zoom=zoom, x=x, y=y),
        headers={"User-Agent": "CaptureGraph (+https://capture-graph.org)"},
    )
    with urllib.request.urlopen(request, timeout=20) as response:
        data = response.read()
    tile = cg.Image.new("png")
    tile.write_bytes(data)
    return tile