Basemap Integration for Drawing Countries and Cities

  • Share this:

Code introduction


This function uses the Basemap library to draw countries and cities on a map. By passing in lists of latitudes, longitudes, and city names, the function marks these cities on the map and displays national boundaries.


Technology Stack : Basemap, Numpy, Matplotlib

Code Type : Drawing function

Code Difficulty : Intermediate


                
                    
import numpy as np
from mpl_toolkits.basemap import Basemap

def draw_countries_and_cities(lats, lons, names):
    """
    This function uses Basemap to draw countries and cities on a map.
    """
    fig, ax = plt.subplots()
    m = Basemap(projection='mill', llcrnrlat=-60, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c')
    m.drawcoastlines()
    m.drawcountries()
    
    for lat, lon, name in zip(lats, lons, names):
        x, y = m(lon, lat)
        m.plot(x, y, marker='o', markersize=8)
        plt.text(x, y, name, fontsize=10, ha='center', va='bottom')
    
    plt.show()