Coverage for pyguymer3/geo/add_OSM_map_background.py: 7%
14 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-08 18:47 +0000
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-08 18:47 +0000
1#!/usr/bin/env python3
3# Define function ...
4def add_OSM_map_background(
5 ax,
6 midLat,
7 res,
8 /,
9 *,
10 debug = __debug__,
11 scale = 1,
12):
13 """Add OpenStreetMap map tiles as a background to a Cartopy axis.
15 Parameters
16 ----------
17 axis : cartopy.mpl.geoaxes.GeoAxesSubplot
18 the axis to add the OpenStreetMap map tiles as a background to
19 midLat : float
20 the latitude of the middle of the figure (in degrees)
21 res : float
22 the resolution of the figure (in m/px)
23 debug : bool, optional
24 print debug statements
25 scale : int, optional
26 the scale of the tiles
28 Notes
29 -----
30 Copyright 2017 Thomas Guymer [1]_
32 References
33 ----------
34 .. [1] PyGuymer3, https://github.com/Guymer/PyGuymer3
35 """
37 # Import standard modules ...
38 import os
40 # Import special modules ...
41 try:
42 import cartopy
43 cartopy.config.update(
44 {
45 "cache_dir" : os.path.expanduser("~/.local/share/cartopy_cache"),
46 }
47 )
48 import cartopy.io.img_tiles
49 except:
50 raise Exception("\"cartopy\" is not installed; run \"pip install --user Cartopy\"") from None
52 # Import sub-functions ...
53 from ..openstreetmap import zoom
55 # **************************************************************************
57 # Calculate the zoom depending on the central latitude and the resolution of
58 # the figure ...
59 z = zoom(midLat, res, scale = scale)
60 if debug:
61 print(f"INFO: The resolution is {0.001 * res:,.1f} km/px and the OpenStreetMap zoom is {z:d}.")
63 # Add OpenStreetMap tiles ...
64 # NOTE: It appears that the background image is drawn at only 72 dpi. If you
65 # zoom in then there are around 4 pixels in the red lines joining the
66 # points together for every pixel in the background image (300 / 72 ~=
67 # 4). Try regenerating a map at 72 dpi and the background image will
68 # be the same resolution as the red lines joining the points together.
69 # NOTE: Line 528 of "cartopy/lib/cartopy/mpl/geoaxes.py" is the "imshow()"
70 # call.
71 # NOTE: Line 71 of "cartopy/lib/cartopy/io/img_tiles.py" is the
72 # "image_for_domain()" definition.
73 # NOTE: Line 588 of "cartopy/lib/cartopy/io/img_tiles.py" is the
74 # "_merge_tiles()" definition. My only guess is that some pixels are
75 # not getting sliced correctly when making the merged image because
76 # you should never do floating-point equalities on line 608.
77 osm = cartopy.io.img_tiles.OSM(
78 cache = True,
79 )
80 ax.add_image(
81 osm,
82 z,
83 interpolation = "none", # NOTE: Due to the use of **kwargs
84 # within Cartopy, this is passed
85 # all the way down the stack to
86 # the ".imshow()" call.
87 )