Creating Maps with Cartopy and Geographical Features

  • Share this:

Code introduction


This function uses the Cartopy library to create a map and add geographical features such as coastline, borders, lakes, and rivers. It also plots a red marker at a specified longitude and latitude.


Technology Stack : Cartopy, NumPy, Matplotlib

Code Type : Map drawing

Code Difficulty : Intermediate


                
                    
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import numpy as np
import matplotlib.pyplot as plt

def plot_map_with_features(lng, lat):
    # Create a map projection.
    proj = ccrs.PlateCarree()
    
    # Create a figure and an axis.
    fig, ax = plt.subplots(subplot_kw={'projection': proj})
    
    # Add some geographical features to the map.
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    ax.add_feature(cfeature.LAKES, alpha=0.5)
    ax.add_feature(cfeature.RIVERS)
    
    # Plot the point on the map.
    ax.plot(lng, lat, marker='o', color='red')
    
    # Set the extent of the map.
    ax.set_extent([lng-5, lng+5, lat-5, lat+5])
    
    # Add a title to the map.
    ax.set_title('Map with Features')
    
    # Show the plot.
    plt.show()