| 1 |
"""Tools for generating maps from a text search.""" |
| 2 |
import geopy as gp |
| 3 |
import numpy as np |
| 4 |
import matplotlib.pyplot as plt |
| 5 |
import warnings |
| 6 |
|
| 7 |
from .tile import howmany, bounds2raster, bounds2img, _sm2ll, _calculate_zoom |
| 8 |
from .plotting import INTERPOLATION, ZOOM, add_attribution |
| 9 |
from . import providers |
| 10 |
from xyzservices import TileProvider |
| 11 |
|
| 12 |
|
| 13 |
_val = np.random.randint(1000000) |
| 14 |
_default_user_agent = f"contextily_user_{_val}" |
| 15 |
|
| 16 |
|
| 17 |
class Place(object): |
| 18 |
"""Geocode a place by name and get its map. |
| 19 |
|
| 20 |
This allows you to search for a name (e.g., city, street, country) and |
| 21 |
grab map and location data from the internet. |
| 22 |
|
| 23 |
Parameters |
| 24 |
---------- |
| 25 |
search : string |
| 26 |
The location to be searched. |
| 27 |
zoom : int or None |
| 28 |
[Optional. Default: None] |
| 29 |
The level of detail to include in the map. Higher levels mean more |
| 30 |
tiles and thus longer download time. If None, the zoom level will be |
| 31 |
automatically determined. |
| 32 |
path : str or None |
| 33 |
[Optional. Default: None] |
| 34 |
Path to a raster file that will be created after getting the place map. |
| 35 |
If None, no raster file will be downloaded. |
| 36 |
zoom_adjust : int or None |
| 37 |
[Optional. Default: None] |
| 38 |
The amount to adjust a chosen zoom level if it is chosen automatically. |
| 39 |
source : xyzservices.providers object or str |
| 40 |
[Optional. Default: OpenStreetMap Humanitarian web tiles] |
| 41 |
The tile source: web tile provider or path to local file. The web tile |
| 42 |
provider can be in the form of a :class:`xyzservices.TileProvider` object or a |
| 43 |
URL. The placeholders for the XYZ in the URL need to be `{x}`, `{y}`, |
| 44 |
`{z}`, respectively. For local file paths, the file is read with |
| 45 |
`rasterio` and all bands are loaded into the basemap. |
| 46 |
IMPORTANT: tiles are assumed to be in the Spherical Mercator |
| 47 |
projection (EPSG:3857), unless the `crs` keyword is specified. |
| 48 |
geocoder : geopy.geocoders |
| 49 |
[Optional. Default: geopy.geocoders.Nominatim()] Geocoder method to process `search` |
| 50 |
|
| 51 |
Attributes |
| 52 |
---------- |
| 53 |
geocode : geopy object |
| 54 |
The result of calling ``geopy.geocoders.Nominatim`` with ``search`` as input. |
| 55 |
s : float |
| 56 |
The southern bbox edge. |
| 57 |
n : float |
| 58 |
The northern bbox edge. |
| 59 |
e : float |
| 60 |
The eastern bbox edge. |
| 61 |
w : float |
| 62 |
The western bbox edge. |
| 63 |
im : ndarray |
| 64 |
The image corresponding to the map of ``search``. |
| 65 |
bbox : list |
| 66 |
The bounding box of the returned image, expressed in lon/lat, with the |
| 67 |
following order: [minX, minY, maxX, maxY] |
| 68 |
bbox_map : tuple |
| 69 |
The bounding box of the returned image, expressed in Web Mercator, with the |
| 70 |
following order: [minX, minY, maxX, maxY] |
| 71 |
""" |
| 72 |
|
| 73 |
def __init__( |
| 74 |
self, |
| 75 |
search, |
| 76 |
zoom=None, |
| 77 |
path=None, |
| 78 |
zoom_adjust=None, |
| 79 |
source=None, |
| 80 |
geocoder=gp.geocoders.Nominatim(user_agent=_default_user_agent), |
| 81 |
): |
| 82 |
self.path = path |
| 83 |
if source is None: |
| 84 |
source = providers.OpenStreetMap.HOT |
| 85 |
self.source = source |
| 86 |
self.zoom_adjust = zoom_adjust |
| 87 |
|
| 88 |
|
| 89 |
resp = geocoder.geocode(search) |
| 90 |
bbox = np.array([float(ii) for ii in resp.raw["boundingbox"]]) |
| 91 |
|
| 92 |
if "display_name" in resp.raw.keys(): |
| 93 |
place = resp.raw["display_name"] |
| 94 |
elif "address" in resp.raw.keys(): |
| 95 |
place = resp.raw["address"] |
| 96 |
else: |
| 97 |
place = search |
| 98 |
self.place = place |
| 99 |
self.search = search |
| 100 |
self.s, self.n, self.w, self.e = bbox |
| 101 |
self.bbox = [self.w, self.s, self.e, self.n] |
| 102 |
self.latitude = resp.latitude |
| 103 |
self.longitude = resp.longitude |
| 104 |
self.geocode = resp |
| 105 |
|
| 106 |
|
| 107 |
self.zoom = ( |
| 108 |
_calculate_zoom(self.w, self.s, self.e, self.n) if zoom is None else zoom |
| 109 |
) |
| 110 |
self.zoom = int(self.zoom) |
| 111 |
if self.zoom_adjust is not None: |
| 112 |
self.zoom += zoom_adjust |
| 113 |
self.n_tiles = howmany(self.w, self.s, self.e, self.n, self.zoom, verbose=False) |
| 114 |
|
| 115 |
|
| 116 |
self._get_map() |
| 117 |
|
| 118 |
def _get_map(self): |
| 119 |
kwargs = {"ll": True} |
| 120 |
if self.source is not None: |
| 121 |
kwargs["source"] = self.source |
| 122 |
|
| 123 |
try: |
| 124 |
if isinstance(self.path, str): |
| 125 |
im, bbox = bounds2raster( |
| 126 |
self.w, self.s, self.e, self.n, self.path, zoom=self.zoom, **kwargs |
| 127 |
) |
| 128 |
else: |
| 129 |
im, bbox = bounds2img( |
| 130 |
self.w, self.s, self.e, self.n, self.zoom, **kwargs |
| 131 |
) |
| 132 |
except Exception as err: |
| 133 |
raise ValueError( |
| 134 |
"Could not retrieve map with parameters: {}, {}, {}, {}, zoom={}\n{}\nError: {}".format( |
| 135 |
self.w, self.s, self.e, self.n, self.zoom, kwargs, err |
| 136 |
) |
| 137 |
) |
| 138 |
|
| 139 |
self.im = im |
| 140 |
self.bbox_map = bbox |
| 141 |
return im, bbox |
| 142 |
|
| 143 |
def plot(self, ax=None, zoom=ZOOM, interpolation=INTERPOLATION, attribution=None): |
| 144 |
""" |
| 145 |
Plot a `Place` object |
| 146 |
... |
| 147 |
|
| 148 |
Parameters |
| 149 |
---------- |
| 150 |
ax : AxesSubplot |
| 151 |
Matplotlib axis with `x_lim` and `y_lim` set in Web |
| 152 |
Mercator (EPSG=3857). If not provided, a new |
| 153 |
12x12 figure will be set and the name of the place |
| 154 |
will be added as title |
| 155 |
zoom : int/'auto' |
| 156 |
[Optional. Default='auto'] Level of detail for the |
| 157 |
basemap. If 'auto', if calculates it automatically. |
| 158 |
Ignored if `source` is a local file. |
| 159 |
interpolation : str |
| 160 |
[Optional. Default='bilinear'] Interpolation |
| 161 |
algorithm to be passed to `imshow`. See |
| 162 |
`matplotlib.pyplot.imshow` for further details. |
| 163 |
attribution : str |
| 164 |
[Optional. Defaults to attribution specified by the source of the map tiles] |
| 165 |
Text to be added at the bottom of the axis. This |
| 166 |
defaults to the attribution of the provider specified |
| 167 |
in `source` if available. Specify False to not |
| 168 |
automatically add an attribution, or a string to pass |
| 169 |
a custom attribution. |
| 170 |
|
| 171 |
Returns |
| 172 |
------- |
| 173 |
ax : AxesSubplot |
| 174 |
Matplotlib axis with `x_lim` and `y_lim` set in Web |
| 175 |
Mercator (EPSG=3857) containing the basemap |
| 176 |
|
| 177 |
Examples |
| 178 |
-------- |
| 179 |
|
| 180 |
>>> lvl = cx.Place('Liverpool') |
| 181 |
>>> lvl.plot() |
| 182 |
|
| 183 |
""" |
| 184 |
im = self.im |
| 185 |
bbox = self.bbox_map |
| 186 |
|
| 187 |
title = None |
| 188 |
axisoff = False |
| 189 |
if ax is None: |
| 190 |
fig, ax = plt.subplots(figsize=(12, 12)) |
| 191 |
title = self.place |
| 192 |
axisoff = True |
| 193 |
ax.imshow(im, extent=bbox, interpolation=interpolation) |
| 194 |
ax.set(xlabel="X", ylabel="Y") |
| 195 |
if isinstance(self.source, (dict, TileProvider)) and attribution is None: |
| 196 |
attribution = self.source.get("attribution") |
| 197 |
if attribution: |
| 198 |
add_attribution(ax, attribution) |
| 199 |
if title is not None: |
| 200 |
ax.set(title=title) |
| 201 |
if axisoff: |
| 202 |
ax.set_axis_off() |
| 203 |
return ax |
| 204 |
|
| 205 |
def __repr__(self): |
| 206 |
s = "Place : {} | n_tiles: {} | zoom : {} | im : {}".format( |
| 207 |
self.place, self.n_tiles, self.zoom, self.im.shape[:2] |
| 208 |
) |
| 209 |
return s |
| 210 |
|
| 211 |
|
| 212 |
def plot_map( |
| 213 |
place, bbox=None, title=None, ax=None, axis_off=True, latlon=True, attribution=None |
| 214 |
): |
| 215 |
"""Plot a map of the given place. |
| 216 |
|
| 217 |
Parameters |
| 218 |
---------- |
| 219 |
place : instance of Place or ndarray |
| 220 |
The map to plot. If an ndarray, this must be an image corresponding |
| 221 |
to a map. If an instance of ``Place``, the extent of the image and name |
| 222 |
will be inferred from the bounding box. |
| 223 |
ax : instance of matplotlib Axes object or None |
| 224 |
The axis on which to plot. If None, one will be created. |
| 225 |
axis_off : bool |
| 226 |
Whether to turn off the axis border and ticks before plotting. |
| 227 |
attribution : str |
| 228 |
[Optional. Default to standard `ATTRIBUTION`] Text to be added at the |
| 229 |
bottom of the axis. |
| 230 |
|
| 231 |
Returns |
| 232 |
------- |
| 233 |
ax : instance of matplotlib Axes object or None |
| 234 |
The axis on the map is plotted. |
| 235 |
""" |
| 236 |
warnings.warn( |
| 237 |
( |
| 238 |
"The method `plot_map` is deprecated and will be removed from the" |
| 239 |
" library in future versions. Please use either `add_basemap` or" |
| 240 |
" the internal method `Place.plot`" |
| 241 |
), |
| 242 |
DeprecationWarning, |
| 243 |
) |
| 244 |
if not isinstance(place, Place): |
| 245 |
im = place |
| 246 |
bbox = bbox |
| 247 |
title = title |
| 248 |
else: |
| 249 |
im = place.im |
| 250 |
if bbox is None: |
| 251 |
bbox = place.bbox_map |
| 252 |
if latlon is True: |
| 253 |
|
| 254 |
w, e, s, n = bbox |
| 255 |
w, s = _sm2ll(w, s) |
| 256 |
e, n = _sm2ll(e, n) |
| 257 |
bbox = [w, e, s, n] |
| 258 |
|
| 259 |
title = place.place if title is None else title |
| 260 |
|
| 261 |
if ax is None: |
| 262 |
fig, ax = plt.subplots(figsize=(15, 15)) |
| 263 |
ax.imshow(im, extent=bbox) |
| 264 |
ax.set(xlabel="X", ylabel="Y") |
| 265 |
if title is not None: |
| 266 |
ax.set(title=title) |
| 267 |
if attribution: |
| 268 |
add_attribution(ax, attribution) |
| 269 |
if axis_off is True: |
| 270 |
ax.set_axis_off() |
| 271 |
return ax |