### Install TileMapBase from source Source: https://github.com/matthewdaws/tilemapbase/blob/master/README.rst Install the library by building from source. This is useful for development or if you need the latest changes. ```bash python setup.py install ``` -------------------------------- ### Install TileMapBase using pip Source: https://github.com/matthewdaws/tilemapbase/blob/master/README.rst Install the library using pip. This is the recommended method for most users. ```bash pip install tilemapbase ``` -------------------------------- ### Initialize TileMapBase Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Plotting over a basemap.ipynb Setup the environment for tile rendering. ```python %matplotlib inline import matplotlib.pyplot as plt import tilemapbase tilemapbase.init(create=True) ``` -------------------------------- ### Initialize Tilemapbase and Fetch Tile Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Projections.ipynb Demonstrates starting the logging service and retrieving a specific tile from the OpenStreetMap source. ```python import tilemapbase tilemapbase.start_logging() tilemapbase.tiles.build_OSM().get_tile(0,0,0) ``` -------------------------------- ### Install TileMapBase directly from GitHub Source: https://github.com/matthewdaws/tilemapbase/blob/master/README.rst Install the library directly from the GitHub repository. This will install the latest version from the master branch. ```bash pip install https://github.com/MatthewDaws/TileMapBase/zipball/master ``` -------------------------------- ### Initializing 25k Raster tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Setup procedure for the TwentyFiveRaster data source. ```python t5k_dir = None tilemapbase.ordnancesurvey.TwentyFiveRaster.init(t5k_dir) source = tilemapbase.ordnancesurvey.TwentyFiveRaster() ``` -------------------------------- ### Import Libraries for GeoPandas and Tilemapbase Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/With geopandas.ipynb Import necessary libraries including matplotlib, geopandas, and tilemapbase. Starts logging for tilemapbase. ```python %matplotlib inline import matplotlib.pyplot as plt import geopandas as gpd import tilemapbase tilemapbase.start_logging() ``` -------------------------------- ### Plotting VectorMap District data Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Examples of plotting VectorMap District tiles with specific extents and overlaying projected coordinates. ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-1.55532, 53.80474, xsize=750) source = tilemapbase.ordnancesurvey.VectorMapDistrict() plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) x, y = tilemapbase.ordnancesurvey.project(-1.55532, 53.80474) x1, y1 = tilemapbase.ordnancesurvey.project(-1.553347, 53.807893) x2, y2 = tilemapbase.ordnancesurvey.project(-1.552304, 53.804356) ax.scatter([x, x1, x2], [y, y1, y2]) None ``` ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-5.71808, 50.06942, xsize=750) plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) x, y = tilemapbase.ordnancesurvey.project(-5.71808, 50.06942) ax.scatter([x], [y]) None ``` ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-3.02516, 58.64389, xsize=750) plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) x, y = tilemapbase.ordnancesurvey.project(-3.02516, 58.64389) ax.scatter([x], [y]) None ``` ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-1.55532, 53.80474, xsize=750) plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) x, y = tilemapbase.ordnancesurvey.project(-1.55532, 53.80474) x1, y1 = tilemapbase.ordnancesurvey.project(-1.553347, 53.807893) x2, y2 = tilemapbase.ordnancesurvey.project(-1.552304, 53.804356) ax.scatter([x, x1, x2], [y, y1, y2]) None ``` -------------------------------- ### Plot Map with Low Quality Tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Plots a map using the defined extent and tiles, similar to the previous example but using `plotlq` which may result in distortion. A scatter point is added to the plot. ```python fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter.plotlq(ax, t) x, y = tilemapbase.project(*my_office) ax.scatter(x,y, marker=".", color="black", linewidth=20) None ``` -------------------------------- ### Render Large Extent Map (Slow) Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Renders a map with a significantly larger extent, which can be slow due to the amount of data processed. This example demonstrates plotting a broader geographical area. ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-1.55532, 53.80474, xsize=10000) plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) ``` -------------------------------- ### Initialize TileMapBase Environment Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Further examples.ipynb Sets up the logging and initial configuration required for tilemapbase operations. ```python %matplotlib inline import matplotlib.pyplot as plt import tilemapbase tilemapbase.start_logging() tilemapbase.init(create=True) ``` -------------------------------- ### Initialize Database Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Initializes the tilemapbase database. Run this only if the DB file does not already exist. ```python # Don't need if you have run before; DB file will already exist. tilemapbase.init(create=True) ``` -------------------------------- ### Build Tile Source Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Further examples.ipynb Initializes the OpenStreetMap tile source. ```python t = tilemapbase.tiles.build_OSM() ``` -------------------------------- ### Initialize Logging Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Initializes tilemapbase and sets up console logging for HTTP requests. Ensure Jupyter notebook is running for console output. ```python # Import, and set to log to the console. (See the console which is running # Jupyter notebook for logging about HTTP requests.) import tilemapbase tilemapbase.start_logging() ``` -------------------------------- ### Initialize tilemapbase Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Aspect ratios.ipynb Initializes the library and checks the current version. ```python %matplotlib inline import matplotlib.pyplot as plt import tilemapbase tilemapbase.init() tilemapbase.__version__ ``` -------------------------------- ### Initialize Image Processing Environment Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Imshow Filters.ipynb Imports necessary libraries and configures Matplotlib for inline display. ```python %matplotlib inline import matplotlib.pyplot as plt import PIL.Image ``` -------------------------------- ### Managing MiniScale and Overview tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Accessing filenames and plotting overview map data. ```python source = tilemapbase.ordnancesurvey.MiniScale() source.filenames ``` ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-1.55532, 53.80474, xsize=75000) plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) ``` ```python source_over = tilemapbase.ordnancesurvey.OverView() print(source_over.filenames) source_over.filename = 'GBOverviewPlus.tif' source_over("SE 1 2") ``` ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-1.55532, 53.80474, xsize=250000) plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) plotter_over = tilemapbase.ordnancesurvey.Plotter(ex, source_over) fig, ax = plt.subplots(ncols=2, figsize=(18,9)) plotter_over.plot(ax[0]) plotter.plot(ax[1]) ``` -------------------------------- ### Use Alternative Tile Sets Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Further examples.ipynb Switches to different tile providers like Stamen or Carto for varied visual styles. ```python t = tilemapbase.tiles.Stamen_Watercolour ``` ```python fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent, t, width=300) plotter.plot(ax, t) x, y = tilemapbase.project(*my_office) ax.scatter(x,y, marker=".", color="black", linewidth=20) None ``` ```python t = tilemapbase.tiles.Carto_Light ``` ```python fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent, t, width=300) plotter.plot(ax, t) x, y = tilemapbase.project(*my_office) ax.scatter(x,y, marker=".", color="black", linewidth=20) None ``` -------------------------------- ### Initialize MasterMap Source Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Initializes the MasterMap data source using the default tile size. Ensure the directory path is correctly set for your local data. ```python mm_dir = None tilemapbase.ordnancesurvey.MasterMap.init(mm_dir) source = tilemapbase.ordnancesurvey.MasterMap() ``` -------------------------------- ### Initialize Cache and Logging Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Initialize the SQLite cache database and enable logging for debugging HTTP requests. The cache must be initialized before any tile fetching operations. ```python import tilemapbase # Initialize the cache (required before first use) # Use create=True the first time to create the database file tilemapbase.init(create=True) # Optionally specify a custom cache file location tilemapbase.init(cache_filename="/path/to/custom_cache.db", create=True) # Enable logging to see HTTP requests (useful for debugging) tilemapbase.start_logging() # Close the cache connection when done tilemapbase.close() ``` -------------------------------- ### Initialize and access the cache Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Cache.ipynb Initializes the tilemapbase environment and retrieves the cache object. ```python import tilemapbase tilemapbase.init(create=True) cache = tilemapbase.get_cache() ``` -------------------------------- ### Configure MasterMap with Smaller Tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Initializes the MasterMap source and overrides the default tile size to 1600 pixels. Requires a separate directory from the standard resolution tiles. ```python # To use the smaller tiles mm_dir = None # Must be a different directory tilemapbase.ordnancesurvey.MasterMap.init(mm_dir) source = tilemapbase.ordnancesurvey.MasterMap() source.tilesize = 1600 ``` -------------------------------- ### Initialize Ordnance Survey Data Directory Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Initializes the tilemapbase library to use Ordnance Survey tiles from a specified local directory. Ensure the directory contains downloaded and unzipped tile data. ```python %matplotlib inline import matplotlib.pyplot as plt import tilemapbase import os datadir = os.path.join("..", "..", "..", "Data", "OS_OpenMap") tilemapbase.ordnancesurvey.init(datadir) ``` -------------------------------- ### Build OpenStreetMap Tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Builds a tile object for OpenStreetMap. ```python # Use open street map t = tilemapbase.tiles.build_OSM() ``` -------------------------------- ### Create High-Resolution Map Exports Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Configure zoom levels and DPI settings to generate high-quality map figures for printing or publication. ```python import matplotlib.pyplot as plt import tilemapbase tilemapbase.init(create=True) location = (-1.554934, 53.804198) extent = tilemapbase.Extent.from_centre_lonlat( location[0], location[1], xsize=0.005, aspect=1.0 ) tiles = tilemapbase.tiles.build_OSM() # Standard resolution plotter plotter = tilemapbase.Plotter(extent, tiles, width=600) print(f"Using zoom level: {plotter.zoom}") # Higher resolution: increase zoom level plotter_hires = tilemapbase.Plotter(extent, tiles, zoom=plotter.zoom + 1) # Create high-DPI figure for print fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter_hires.plot(ax) # Add point marker x, y = tilemapbase.project(*location) ax.scatter(x, y, marker="o", color="red", s=100, zorder=5) # Save at high DPI for printing fig.savefig("map_print.pdf", dpi=300, bbox_inches='tight') fig.savefig("map_print.png", dpi=300, bbox_inches='tight') plt.show() # For very large areas, use allow_large=True (downloads many tiles) large_extent = tilemapbase.Extent.from_lonlat(-2.0, -1.0, 53.5, 54.0) large_plotter = tilemapbase.Plotter(large_extent, tiles, width=2000) fig, ax = plt.subplots(figsize=(20, 20)) large_plotter.plot(ax, allow_large=True) # Allows >128 tiles ``` -------------------------------- ### Configure Tile Providers Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Access built-in tile providers or define custom ones. OpenStreetMap requires a User-Agent header to comply with usage policies. ```python import tilemapbase from tilemapbase import tiles tilemapbase.init(create=True) # OpenStreetMap (requires User-Agent header) osm = tiles.build_OSM() # Default User-Agent: "TileMapBase" osm_custom = tiles.build_OSM(headers={"User-Agent": "MyApp/1.0"}) # OpenStreetMap Humanitarian osm_hot = tiles.build_OSM_Humanitarian() # Stamen maps (no headers required) toner = tiles.Stamen_Toner toner_lite = tiles.Stamen_Toner_Lite terrain = tiles.Stamen_Terrain watercolor = tiles.Stamen_Watercolour # Carto maps (free for non-commercial use) carto_light = tiles.Carto_Light carto_dark = tiles.Carto_Dark carto_light_no_labels = tiles.Carto_Light_No_Labels carto_dark_no_labels = tiles.Carto_Dark_No_Labels # Create custom tile provider custom_tiles = tiles.Tiles( request_string="https://example.com/tiles/{zoom}/{x}/{y}.png", source_name="CustomProvider", tilesize=256, maxzoom=19, headers={"User-Agent": "MyApp"} ) # Fetch individual tiles tile_image = osm.get_tile(x=123, y=456, zoom=15) # Returns PIL Image ``` -------------------------------- ### Splitting OpenMapLocal tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Demonstrates using TileSplitter to process OpenMapLocal data and convert coordinates to the OS National Grid. ```python source = tilemapbase.ordnancesurvey.OpenMapLocal() source = tilemapbase.ordnancesurvey.TileSplitter(source, 200) x, y = tilemapbase.ordnancesurvey.project(-1.55532, 53.80474) print(tilemapbase.ordnancesurvey.coords_to_os_national_grid(x, y)) source("SE 29383 34363") ``` -------------------------------- ### Import Libraries Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Imports necessary libraries for plotting and tilemapbase functionality. ```python %matplotlib inline import matplotlib.pyplot as plt ``` -------------------------------- ### Dump cache to directory Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Cache.ipynb Exports all cached files into a specified directory. ```python # This dumps all file... import os os.mkdir("dump") cache.dump("dump") ``` -------------------------------- ### Retrieve and display a specific tile Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Cache.ipynb Fetches raw data for a specific tile from the cache and opens it as a PIL image. ```python data, time = cache.get_from_cache(('OSM', 1, 1, 1)) import io, PIL.Image file = io.BytesIO(data) PIL.Image.open(file) ``` -------------------------------- ### Compare EPSG:3857 and EPSG:3785 Projections Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Projections.ipynb Verifies that EPSG:3857 and EPSG:3785 are identical up to a rescaling factor by comparing random coordinate projections. ```python import pyproj p3857 = pyproj.Proj({"init": "epsg:3857"}) p3785 = pyproj.Proj({"init": "epsg:3785"}) ``` ```python scale = 20037508.342789244 def rescale(x, y): return ((x - 0.5) * 2 * scale, (0.5 - y) * 2 * scale) import random, math diffs = [] for _ in range(10000): x = random.random() * 360 - 180 y = random.random() * 170 - 85 assert p3857(x, y) == p3785(x, y) xx, yy = p3857(x, y) xxx, yyy = rescale(*tilemapbase.project(x, y)) diffs.append( math.sqrt((xx - xxx)**2 + (yy - yyy)**2) ) ``` ```python max(diffs), sum(diffs) / 10000 ``` -------------------------------- ### Visualize Interpolation Methods on Cropped Image Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Imshow Filters.ipynb Iterates through a list of interpolation methods to display the cropped image in a 4x4 grid. ```python interpolations = ["nearest", "bilinear", "bicubic", "spline16", "spline36", "hanning", "hamming", "hermite", "kaiser", "quadric", "catrom", "gaussian", "bessel", "mitchell", "sinc", "lanczos"] fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(16,16)) for a,name in zip(ax.flatten(), interpolations): a.imshow(img, interpolation=name) a.set(title=name) ``` -------------------------------- ### Load and Crop Image Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Imshow Filters.ipynb Opens an image file and extracts a specific region using crop coordinates. ```python image = PIL.Image.open("test.png") img = image.crop((100,20,150,70)) image ``` -------------------------------- ### Project Coordinates to Web Mercator Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Plotting over a basemap.ipynb Convert longitude and latitude lists into Web Mercator coordinates for plotting. ```python # The path to plot longs = [-1.554934, -1.555, -1.5552, -1.554] lats = [53.804198, 53.80416, 53.8041, 53.8042] # Convert to web mercator path = [tilemapbase.project(x,y) for x,y in zip(longs, lats)] x, y = zip(*path) ``` -------------------------------- ### Visualize Interpolation Methods on Original Image Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Imshow Filters.ipynb Applies various interpolation methods to the original image in a 4x4 grid layout. ```python fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(11,12)) for a,name in zip(ax.flatten(), interpolations): a.imshow(image, interpolation=name) a.set(title=name) ``` -------------------------------- ### Create GeoDataFrame Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Wards in Leeds.ipynb Converts the fetched boundary data into a GeoDataFrame for spatial analysis and manipulation. ```python import geopandas as gpd frame = gpd.GeoDataFrame.from_features(shapes.values()) ``` -------------------------------- ### Check for Available OpenMapLocal Tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Verifies which Ordnance Survey OpenMapLocal tiles are available in the initialized data directory. This helps confirm that the data has been correctly set up. ```python # We have only downloaded and unzipped the files necessary for this notebook to run. tilemapbase.ordnancesurvey.OpenMapLocal.found_tiles() ``` -------------------------------- ### Fetch ONS Boundary Data Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Wards in Leeds.ipynb Iterates through the ward data, fetches boundary information from ONS URLs, and stores it in a dictionary. ```python import json url = "http://statistics.data.gov.uk/boundaries/{}.json" shapes = dict() for ward in wards: response = requests.get(url.format(ward.code)) shapes[ward.code] = json.loads(response.content.decode("utf8")) ``` -------------------------------- ### Plot Data on Tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Plotting over a basemap.ipynb Render the map tiles and overlay the path using Matplotlib axes. ```python fig, ax = plt.subplots(figsize=(10,10)) plotter = tilemapbase.Plotter(extent, tilemapbase.tiles.build_OSM(), width=600) plotter.plot(ax) ax.plot(x, y, "ro-") ``` -------------------------------- ### Set CRS and Reproject Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Wards in Leeds.ipynb Sets the Coordinate Reference System to WGS84 and then reprojects the GeoDataFrame to Web Mercator for tile map compatibility. ```python # Set projection as lon/lat, then reproject to "web mercator" frame.crs = {"init": "EPSG:4326"} frame = frame.to_crs({"init": "EPSG:3857"}) ``` -------------------------------- ### Plot with Tilemapbase Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Wards in Leeds.ipynb Visualizes the GeoDataFrame on an interactive map using Tilemapbase, overlaying ward boundaries. ```python import tilemapbase fig, ax = plt.subplots(figsize=(10,10)) extent = tilemapbase.extent_from_frame(frame, buffer=5) plotter = tilemapbase.Plotter(extent, tilemapbase.tiles.OSM, width=600) plotter.plot(ax) frame.plot(ax=ax, column="WD15NM", categorical=True, alpha=0.2) None ``` -------------------------------- ### Create GeoDataFrame from Features Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/With geopandas.ipynb Constructs a GeoDataFrame from a list of GeoJSON-like features, each with properties and geometry. Ensure your input data is correctly formatted. ```python features = [ { "properties" : {"name" : "My office"}, "geometry" : { "type": "Point", "coordinates" : (-1.554934, 53.804198)} }, { "properties" : {"name" : "Library"}, "geometry" : { "type": "Point", "coordinates" : (-1.554664, 53.806221)} }, { "properties" : {"name" : "Gym"}, "geometry" : { "type": "Point", "coordinates" : (-1.553366, 53.804251)} } ] frame = gpd.GeoDataFrame.from_features(features) ``` -------------------------------- ### Coordinate Projection Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Convert between longitude/latitude and Web Mercator projected coordinates. Note that project() expects (longitude, latitude) input order. ```python import tilemapbase # Project longitude/latitude to Web Mercator coordinates # Coordinates are (longitude, latitude) - longitude first! longitude, latitude = -1.554934, 53.804198 # University of Leeds x, y = tilemapbase.project(longitude, latitude) print(f"Projected coordinates: ({x}, {y})") # Output: Projected coordinates: (0.4956724..., 0.3219964...) # Convert back to longitude/latitude lon, lat = tilemapbase.to_lonlat(x, y) print(f"Original coordinates: ({lon}, {lat})") # Output: Original coordinates: (-1.554934, 53.804198) ``` -------------------------------- ### Save High-Resolution Figure Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Demonstrates how to save a figure with a higher DPI for printing. This will create a high-DPI PDF file. ```python # fig.savefig("test.pdf", dpi=200) ``` -------------------------------- ### Define Extent and Plot Tiles Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Define a map extent using longitude and latitude, then plot the tiles using the Plotter class. ```python extent = os_tiles.Extent.from_centre_lonlat(-1.554934, 53.804198, xsize=5000) # Plot OS tiles fig, ax = plt.subplots(figsize=(10, 10)) plotter = os_tiles.Plotter(extent, source) plotter.plot(ax) plt.show() ``` -------------------------------- ### Work with UK Ordnance Survey Tiles Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Utilize TileMapBase for UK Ordnance Survey raster tiles, including OS OpenMap Local, VectorMap District, and MiniScale. Convert between longitude/latitude and OS National Grid references, and create map extents based on grid references. ```python import matplotlib.pyplot as plt import tilemapbase from tilemapbase import ordnancesurvey as os_tiles # Initialize with directory containing OS tiles os_tiles.init("/path/to/ordnance_survey_tiles") # Convert longitude/latitude to OS National Grid grid_ref, eastings, northings = os_tiles.to_os_national_grid(-1.554934, 53.804198) print(f"Grid reference: {grid_ref}") # e.g., "SE 29383 34363" # Convert grid reference to coordinates x, y = os_tiles.os_national_grid_to_coords("SE 29383 34363") print(f"Coordinates: ({x}, {y})") # Create tile source (OpenMap Local - 5km tiles at 1m resolution) source = os_tiles.OpenMapLocal() print(f"Available grid codes: {os_tiles.OpenMapLocal.found_tiles()}") # Other tile sources vector_source = os_tiles.VectorMapDistrict() # 10km tiles mini_source = os_tiles.MiniScale() # Whole UK overview # Create extent centered on OS grid reference extent = os_tiles.Extent.from_centre_grid("SE 29383 34363", xsize=5000, aspect=1.0) ``` -------------------------------- ### Read CSV Data Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Wards in Leeds.ipynb Initializes a CSV reader and skips the header row. ```python reader = csv.reader(file) next(reader) ``` -------------------------------- ### Plot Using Pyplot Interface Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Plotting over a basemap.ipynb Alternative method to plot data directly using the pyplot interface. ```python # Or using the plt interface plotter.plot(plt.axes()) plt.plot(x,y, "ro-") ``` -------------------------------- ### Resizing tiles with TileScalar Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Applying scaling to map tiles for zooming purposes. ```python source = tilemapbase.ordnancesurvey.VectorMapDistrict() scaled = tilemapbase.ordnancesurvey.TileScalar(source, 500) scaled("SE 12345 65432") ``` -------------------------------- ### Check for Available VectorMapDistrict Tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Verifies which Ordnance Survey VectorMapDistrict tiles are available in the initialized data directory. This confirms the presence and accessibility of VectorMapDistrict data. ```python tilemapbase.ordnancesurvey.VectorMapDistrict.found_tiles() ``` -------------------------------- ### Plotting 250k Raster tiles Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Usage of TwoFiftyScale source for plotting larger scale map extents. ```python source = tilemapbase.ordnancesurvey.TwoFiftyScale() ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-1.55532, 53.80474, xsize=15000) plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) x, y = tilemapbase.ordnancesurvey.project(-1.55532, 53.80474) x1, y1 = tilemapbase.ordnancesurvey.project(-1.553347, 53.807893) x2, y2 = tilemapbase.ordnancesurvey.project(-1.552304, 53.804356) ax.scatter([x, x1, x2], [y, y1, y2]) None ``` -------------------------------- ### Plot GeoDataFrame on a Tilemap Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/With geopandas.ipynb Creates a plot with a specified extent and tile source (OpenStreetMap), then overlays the GeoDataFrame. Ensure the GeoDataFrame's CRS matches the map projection. ```python fig, ax = plt.subplots(figsize=(10,10)) plotter = tilemapbase.Plotter(extent, tilemapbase.tiles.build_OSM(), width=400) plotter.plot(ax) frame.plot(ax=ax, column="name") ax.legend(frame.name) None ``` -------------------------------- ### Manage Tile Cache Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Access and manage the tile cache, which stores downloaded tiles in a SQLite database. Query cached tiles, clean old tiles based on a cutoff date, dump cache contents to a directory, or remove specific tiles. ```python import tilemapbase from datetime import datetime, timedelta tilemapbase.init(create=True) # Get access to the cache cache = tilemapbase.get_cache() # Query all cached tiles # Returns list of ((name, x, y, zoom), timestamp) tuples cached_tiles = cache.query() for (name, x, y, zoom), timestamp in cached_tiles[:5]: print(f"Provider: {name}, Tile: ({x}, {y}) @ zoom {zoom}, Cached: {timestamp}") # Remove tiles older than 30 days cutoff_date = datetime.now() - timedelta(days=30) cache.clean(cutoff_date) # Dump all cached tiles to a directory import os output_dir = "/tmp/tile_dump" os.makedirs(output_dir, exist_ok=True) cache.dump(output_dir) # Creates structure: output_dir/ProviderName/ZoomLevel/x_y.png # Remove specific tile from cache cache.remove(("OSM", 123, 456, 15)) ``` -------------------------------- ### Display Cropped Image Object Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Imshow Filters.ipynb Displays the cropped image object. ```python img ``` -------------------------------- ### Query cache contents Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Cache.ipynb Retrieves a list of cached tiles and their associated timestamps. ```python contents = cache.query() contents[:4] ``` -------------------------------- ### Optimize Tile Plotting Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Use TileSplitter or TileScalar to manage tile sizes for faster or resized plotting. ```python # Use TileSplitter for faster plotting with smaller tiles split_source = os_tiles.TileSplitter(source, newsize=1000) plotter = os_tiles.Plotter(extent, split_source) # Use TileScalar to resize tiles scaled_source = os_tiles.TileScalar(source, newsize=2000) ``` -------------------------------- ### Fetch Leeds Ward Data Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Wards in Leeds.ipynb Retrieves the initial ward data from a CSV file hosted online using the requests library. ```python import csv, requests url = "https://aql.datapress.com/leeds/dataset/wards-in-leeds/wardsgeoarea.csv" response = requests.get(url) ``` -------------------------------- ### Render Map Tiles with Plotter Class Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Use the Plotter class to render map tiles to Matplotlib axes. Automatically determines zoom level based on desired pixel dimensions or exact zoom. Supports high-quality tile assembly or faster lower-quality plotting. ```python import matplotlib.pyplot as plt import tilemapbase tilemapbase.init(create=True) # Set up the map extent and tile provider my_office = (-1.554934, 53.804198) degree_range = 0.003 extent = tilemapbase.Extent.from_lonlat( my_office[0] - degree_range, my_office[0] + degree_range, my_office[1] - degree_range, my_office[1] + degree_range ) extent = extent.to_aspect(1.0) tiles = tilemapbase.tiles.build_OSM() # Create plotter with target width in pixels (auto-selects zoom) plotter = tilemapbase.Plotter(extent, tiles, width=600) # Or specify height instead plotter = tilemapbase.Plotter(extent, tiles, height=400) # Or specify exact zoom level plotter = tilemapbase.Plotter(extent, tiles, zoom=17) # Plot to matplotlib axes (high quality - assembles tiles first) fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter.plot(ax) # Add markers on the map x, y = tilemapbase.project(*my_office) ax.scatter(x, y, marker=".", color="red", s=100) plt.savefig("map.png", dpi=150) plt.show() # Lower quality but faster plotting (multiple imshow calls) fig, ax = plt.subplots(figsize=(8, 8)) plotter.plotlq(ax) plt.show() # Get tiles as a single PIL Image image = plotter.as_one_image() image.save("basemap.png") ``` -------------------------------- ### Translate Extent and Plot Map Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Translates a given extent object to a new center longitude and latitude, then creates a plotter and plots the map. ```python extent1 = extent.with_centre_lonlat(-1.558, 53.804198) plotter2 = tilemapbase.Plotter(extent1, t, width=600) fig, ax = plt.subplots(figsize=(8, 8), dpi=100) plotter2.plot(ax) ``` -------------------------------- ### Integrate with GeoPandas DataFrames Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Utilize TileMapBase utilities for seamless integration with GeoPandas GeoDataFrames. Automatically calculates map extent from GeoDataFrame features with an optional buffer. Supports coordinate projection handling for compatibility with tile systems. ```python import matplotlib.pyplot as plt import geopandas as gpd import tilemapbase tilemapbase.init(create=True) # Create a GeoDataFrame with point features features = [ {"properties": {"name": "Office"}, "geometry": {"type": "Point", "coordinates": (-1.554934, 53.804198)}}, {"properties": {"name": "Library"}, "geometry": {"type": "Point", "coordinates": (-1.554664, 53.806221)}}, {"properties": {"name": "Gym"}, "geometry": {"type": "Point", "coordinates": (-1.553366, 53.804251)}} ] frame = gpd.GeoDataFrame.from_features(features) frame = frame.set_crs("EPSG:4326") # Convert to Web Mercator for compatibility with tiles frame = frame.to_crs("EPSG:3857") # Auto-calculate extent from GeoDataFrame with buffer extent = tilemapbase.extent_from_frame(frame, buffer=25) # 25% buffer # Plot basemap with GeoPandas overlay fig, ax = plt.subplots(figsize=(10, 10)) plotter = tilemapbase.Plotter(extent, tilemapbase.tiles.build_OSM(), width=400) plotter.plot(ax) frame.plot(ax=ax, column="name", legend=True) plt.show() # Extract point coordinates for manual plotting (faster than GeoPandas plot) x_coords, y_coords = tilemapbase.mapping.points_from_frame(frame) ax.scatter(x_coords, y_coords, c='red', s=50) ``` -------------------------------- ### Define Map Extents Source: https://context7.com/matthewdaws/tilemapbase/llms.txt Create and manipulate rectangular regions in Web Mercator space using the Extent class. These can be derived from coordinates, centered points, or scaled for zoom levels. ```python import tilemapbase # Create extent from longitude/latitude bounds extent = tilemapbase.Extent.from_lonlat( longitude_min=-1.56, longitude_max=-1.55, latitude_min=53.80, latitude_max=53.81 ) # Create extent centered on a point with specified size my_location = (-1.554934, 53.804198) extent = tilemapbase.Extent.from_centre_lonlat( longitude=my_location[0], latitude=my_location[1], xsize=0.01, # Width in Web Mercator units aspect=1.0 # Aspect ratio (width/height) ) # Alternative: create from degree range degree_range = 0.003 extent = tilemapbase.Extent.from_lonlat( my_location[0] - degree_range, my_location[0] + degree_range, my_location[1] - degree_range, my_location[1] + degree_range ) # Adjust aspect ratio (shrinks to fit by default) extent = extent.to_aspect(1.0) # Translate the extent to a new center new_extent = extent.with_centre_lonlat(-1.558, 53.804198) # Zoom in by scaling (scale=2 means 2x zoom) zoomed_extent = extent.with_scaling(2) # Convert to EPSG:3857 projection for GeoPandas compatibility extent_3857 = extent.to_project_3857() ``` -------------------------------- ### Plot Map with Tiles and Scatter Point Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Plots a map using the defined extent and tiles, then adds a scatter point at a specific projected coordinate. This method assembles tiles into a single image before displaying. ```python # On my desktop, DPI gets scaled by 0.75 fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent, t, width=600) plotter.plot(ax, t) x, y = tilemapbase.project(*my_office) ax.scatter(x,y, marker=".", color="black", linewidth=20) None ``` -------------------------------- ### Define Bounding Box Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Aspect ratios.ipynb Creates a named tuple to store geographic bounding box coordinates. ```python import collections BBox = collections.namedtuple("BBox", "minx maxx miny maxy") ``` ```python bbox = BBox(-2.8197899, -0.691999, 50.5380771, 50.8583224) ``` -------------------------------- ### Define Map Extent Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Plotting over a basemap.ipynb Create a map extent centered on specific coordinates using longitude and latitude. ```python # Define the `extent` my_office = (-1.554934, 53.804198) degree_range = 0.003 extent = tilemapbase.Extent.from_lonlat(my_office[0] - degree_range, my_office[0] + degree_range, my_office[1] - degree_range, my_office[1] + degree_range) extent = extent.to_aspect(1.0) extent ``` -------------------------------- ### Transform Coordinates to British National Grid Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Projections.ipynb Uses pyproj to transform WGS84 coordinates into the British National Grid (EPSG:27700) system. ```python import pyproj, functools bng = pyproj.Proj(init="epsg:27700") wgs84 = pyproj.Proj(init="epsg:4326") def project(lon, lat): return pyproj.transform(wgs84, bng, lon, lat) print(project(-1.55532, 53.80474)) print(project(-5.71808, 50.06942)) print(project(-3.02516, 58.64389)) ``` -------------------------------- ### Plot Map with Varying Widths Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Further examples.ipynb Adjusts the width parameter to change the zoom level and tile detail. ```python fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent, t, width=600) plotter.plot(ax, t) x, y = tilemapbase.project(*my_office) ax.scatter(x,y, marker=".", color="black", linewidth=20) None ``` ```python fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent, t, width=1200) plotter.plot(ax, t) x, y = tilemapbase.project(*my_office) ax.scatter(x,y, marker=".", color="black", linewidth=20) None ``` ```python fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent, t, width=300) plotter.plot(ax, t) x, y = tilemapbase.project(*my_office) ax.scatter(x,y, marker=".", color="black", linewidth=20) None ``` -------------------------------- ### Plot Map Centered on Specific Longitude/Latitude Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Plots a map centered on a given longitude and latitude using OpenMapLocal tiles. The center point is also marked on the map. ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-5.71808, 50.06942, xsize=750) source = tilemapbase.ordnancesurvey.OpenMapLocal() plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) x, y = tilemapbase.ordnancesurvey.project(-5.71808, 50.06942) ax.scatter([x], [y]) None ``` -------------------------------- ### Set and Check CRS for GeoDataFrame Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/With geopandas.ipynb Sets the Coordinate Reference System (CRS) of the GeoDataFrame to EPSG:4326 (WGS 84). Always verify the CRS after setting it. ```python frame = frame.set_crs("EPSG:4326") frame.crs ``` -------------------------------- ### Apply Alpha Transparency Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Further examples.ipynb Reduces background visibility by setting an alpha value in the plot method. ```python fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent, t, width=300) plotter.plot(ax, t, alpha=0.5) x, y = tilemapbase.project(*my_office) ax.scatter(x,y, marker=".", color="black", linewidth=20) None ``` -------------------------------- ### Plot Map Extent Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Aspect ratios.ipynb Plots a map extent using OpenStreetMap tiles and a specified plotter width. ```python t = tilemapbase.tiles.build_OSM() extent = tilemapbase.Extent.from_lonlat( longitude_min=bbox.minx, longitude_max=bbox.maxx, latitude_min=bbox.miny, latitude_max=bbox.maxy) #extent = extent.to_aspect(1) fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent, t, width=600) plotter.plot(ax) ``` -------------------------------- ### Plot Map Centered on Northern Scotland Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Plots a map centered on a specific location in Northern Scotland using OpenMapLocal tiles. The central point is marked on the generated map. ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-3.02516, 58.64389, xsize=750) source = tilemapbase.ordnancesurvey.OpenMapLocal() plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) x, y = tilemapbase.ordnancesurvey.project(-3.02516, 58.64389) ax.scatter([x], [y]) None ``` -------------------------------- ### Plot Map with Increased Zoom Level Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Creates and plots a map with an increased zoom level compared to the previous plotter. A scatter point is added to mark a location. ```python plotter1 = tilemapbase.Plotter(plotter.extent, t, zoom = plotter.zoom + 1) fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter1.plot(ax, t) x, y = tilemapbase.project(*my_office) ax.scatter(x,y, marker=".", color="black", linewidth=20) None ``` -------------------------------- ### Plot GeoDataFrame Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Wards in Leeds.ipynb Generates a basic plot of the GeoDataFrame using matplotlib. ```python %matplotlib inline import matplotlib.pyplot as plt frame.plot() ``` -------------------------------- ### Process CSV Response Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Wards in Leeds.ipynb Decodes the response content and prepares it for CSV parsing using io.StringIO. ```python import io file = io.StringIO(response.content.decode("utf8")) ``` -------------------------------- ### Convert GeoDataFrame CRS to EPSG:3857 Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/With geopandas.ipynb Transforms the GeoDataFrame from its current CRS (EPSG:4326) to the Web Mercator projection (EPSG:3857). This is often required for web map tiles. ```python frame = frame.to_crs("EPSG:3857") frame ``` -------------------------------- ### Plot University of Leeds Campus Map Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Ordnance Survey.ipynb Plots a map centered on the University of Leeds campus using OpenMapLocal tiles. It also marks specific points of interest on the map using projected coordinates. ```python ex = tilemapbase.ordnancesurvey.Extent.from_centre_lonlat(-1.55532, 53.80474, xsize=750) source = tilemapbase.ordnancesurvey.OpenMapLocal() plotter = tilemapbase.ordnancesurvey.Plotter(ex, source) fig, ax = plt.subplots(figsize=(10,10)) plotter.plot(ax) x, y = tilemapbase.ordnancesurvey.project(-1.55532, 53.80474) x1, y1 = tilemapbase.ordnancesurvey.project(-1.553347, 53.807893) x2, y2 = tilemapbase.ordnancesurvey.project(-1.552304, 53.804356) ax.scatter([x, x1, x2], [y, y1, y2]) None ``` -------------------------------- ### Define Ward Named Tuple Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Wards in Leeds.ipynb Creates a named tuple for cleaner ward data representation and processes the reader into a list of Ward objects. ```python import collections Ward = collections.namedtuple("Ward", ["code", "name", "url"]) wards = [Ward(*row) for row in reader] ``` -------------------------------- ### Convert Extent to EPSG:3857 and Plot Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Example.ipynb Converts the map extent to the EPSG:3857 projection, which is compatible with other GIS systems. A plotter is created with this new extent and the map is plotted. ```python extent2 = extent1.to_project_3857() plotter3 = tilemapbase.Plotter(extent2, t, width=600) fig, ax = plt.subplots(figsize=(8, 8), dpi=100) plotter3.plot(ax) ``` -------------------------------- ### Adjust Aspect Ratio Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/Aspect ratios.ipynb Adjusts the map extent to a specific aspect ratio before plotting. ```python extent1 = extent.to_aspect(1) ``` ```python fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent1, t, width=600) plotter.plot(ax) ``` ```python extent2 = extent.to_aspect(1, False) ``` ```python fig, ax = plt.subplots(figsize=(8, 8), dpi=100) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plotter = tilemapbase.Plotter(extent2, t, width=600) plotter.plot(ax) ``` -------------------------------- ### Calculate Map Extent from GeoDataFrame Source: https://github.com/matthewdaws/tilemapbase/blob/master/notebooks/With geopandas.ipynb Determines the map extent based on the GeoDataFrame's boundaries, with an optional buffer. Adjust the buffer value to control the padding around the features. ```python extent = tilemapbase.extent_from_frame(frame, buffer = 25) ```