Last active
December 9, 2023 19:12
-
-
Save samilkorkmaz/98eb26592351257975aa5cb1db5246a8 to your computer and use it in GitHub Desktop.
plot_world_map_with_raster
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Download raster (*.tif) files from https://www.naturalearthdata.com/downloads/50m-raster-data/ | |
import matplotlib.pyplot as plt | |
import cartopy.crs as ccrs | |
import rasterio | |
from rasterio.plot import show | |
class InteractiveMap: | |
def __init__(self, raster_path): | |
self.raster_path = raster_path | |
self.fig, self.ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()}) | |
self._init_map() | |
self._connect_events() | |
def _init_map(self): | |
with rasterio.open(self.raster_path) as raster: | |
#self.ax.set_extent(raster.bounds, crs=ccrs.PlateCarree()) | |
# The extent is defined as [west, east, south, north]. | |
self.ax.set_extent([20, 50, 30, 50.0]) | |
self.ax.coastlines() | |
show(raster, ax=self.ax, transform=ccrs.PlateCarree()) | |
def _connect_events(self): | |
self.fig.canvas.mpl_connect('scroll_event', self._on_zoom) | |
self.fig.canvas.mpl_connect('button_press_event', self._on_press) | |
self.fig.canvas.mpl_connect('button_release_event', self._on_release) | |
self.fig.canvas.mpl_connect('motion_notify_event', self._on_motion) | |
self.pressed = False | |
def _on_zoom(self, event): | |
scale_factor = 0.5 if event.button == 'up' else 2.0 | |
x_min, x_max = self.ax.get_xlim() | |
y_min, y_max = self.ax.get_ylim() | |
x_range = (x_max - x_min) * scale_factor | |
y_range = (y_max - y_min) * scale_factor | |
self.ax.set_xlim([event.xdata - x_range / 2, event.xdata + x_range / 2]) | |
self.ax.set_ylim([event.ydata - y_range / 2, event.ydata + y_range / 2]) | |
self.ax.figure.canvas.draw() | |
def _on_press(self, event): | |
if event.button == 3: # Right mouse button | |
self.press_x, self.press_y = event.xdata, event.ydata | |
self.pressed = True | |
def _on_release(self, event): | |
self.pressed = False | |
def _on_motion(self, event): | |
if not self.pressed or event.xdata is None or event.ydata is None: | |
return | |
dx = event.xdata - self.press_x | |
dy = event.ydata - self.press_y | |
self.press_x, self.press_y = event.xdata, event.ydata | |
x_min, x_max = self.ax.get_xlim() | |
y_min, y_max = self.ax.get_ylim() | |
self.ax.set_xlim([x_min - dx, x_max - dx]) | |
self.ax.set_ylim([y_min - dy, y_max - dy]) | |
self.ax.figure.canvas.draw() | |
# Replace 'path_to_your_geotiff.tif' with the path to your GeoTIFF file | |
interactive_map = InteractiveMap('HYP_50M_SR_W.tif') | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment