SoFunction
Updated on 2024-11-14

Python-based implementation of drawing your own world map

Python is so popular because it can be used as a research tool not only in the field of science and technology but also in many other disciplines, and mapping is one of its functions.

Today we use one of the matplot toolkits mpl_toolkits to map the world, this is a simple visualization tool, if you wish to draw more complex maps, you can consider using the Google Maps API, but this is beyond the scope of our discussion today.

1. Preparation

Before you start, you need to make sure that Python and pip have been successfully installed on your computer, if not, visit this article:Super Detailed Python Installation Guide Perform the installation.

(Option 1)If your goal with Python is data analysis, you can just install theAnacondaIt has built-in Python and pip.

(Option 2)In addition, it is recommended to useVSCode EditorIt has many advantages

Please choose one of the following ways to enter commands to install dependencies

1. Windows environment Open Cmd (Start-Run-CMD).

2. MacOS environment Open Terminal (command+space to enter Terminal).

3. If you are using a VSCode editor or Pycharm, you can use Terminal directly from the bottom of the interface.

pip install numpy
pip install matplotlib

In order to use mpl_toolkits, it is not enough to install matplotlib alone, we also need to install basemap separately, if you have already installed Anaconda, this step is very easy, just type the following command to install it:

conda install basemap

If not, it's slightly more problematic:

1. Install geos.pip install geos2. Download basemap according to your Python version.

/~gohlke/pythonlibs/#basemap

Note that the number after cp is the version of Python. (hit ctrl+F on the page and type basemap to quickly locate it)

3. Go to the file's directory under cmd and run

pip install basemap‑1.2.1‑cp37‑cp37m‑win_amd64.whl

2. Simple map

Let's start drawing a globe with the center pointing to China:

# Import the required packages
import numpy as np
import  as plt
from mpl_toolkits.basemap import Basemap

# Initialize graphics
(figsize=(8, 8))
# Base map: circle, lat_0: latitude; lon_o: longitude, (113,29) is Wuhan
m = Basemap(projection='ortho', resolution=None, lat_0=29, lon_0=113)
# Base color
(scale=0.5)
# Show
()

The focus here is on Basemap, specifying the center where you want to place it.

The result is pretty good. Not only that, but it's actually more than just an image, it's a fully functional matplot canvas. This also means that you are able to draw lines on it! Let's zoom into the map, go to the China region, and mark the location of Shenzhen:

# Import the required packages
import numpy as np
import  as plt
from mpl_toolkits.basemap import Basemap

# The following three lines are designed to allow matplot to display Chinese characters
from pylab import mpl
['-serif'] = ['FangSong']
['axes.unicode_minus'] = False

fig = (figsize=(8, 8))
# Note the addition of a couple of new parameters, width and height, which are used to control the scale of the zoom.
# represents the width and height of the projection respectively (8E6 represents 8x10^6 meters)
m = Basemap(projection='lcc', resolution=None,
            width=8E6, height=8E6,
            lat_0=23, lon_0=113,)
(scale=0.5)

# Here's the latitude and longitude: (longitude, latitude) #
x, y = m(113, 23)
(x, y, 'ok', markersize=5) 
(x, y, 'Shenzhen', fontsize=12, color="red") 
()

Don't use the blue background image, it's not very clear to see, let's switch to the embossed type:

You can clearly see the geographical features such as mountains and hills. You can also do connecting lines for certain cities or plot certain areas between latitude and longitude, depending on your needs. Don't forget, this is a matplotlib editable canvas.

3. World map

Next, we unfold the above world map into a planar figure with latitude and longitude lines.

# Import the required packages
import numpy as np
import  as plt
from mpl_toolkits.basemap import Basemap
from itertools import chain


def draw_map(m, scale=0.2):
    # Draw embossed images with shadows
    (scale=scale)

    # Cut according to latitude and longitude, one line for every 13 degrees
    lats = ((-90, 90, 13))
    lons = ((-180, 180, 13))

    # Collect all the lines
    lat_lines = chain(*(tup[1][0] for tup in ()))
    lon_lines = chain(*(tup[1][0] for tup in ()))
    all_lines = chain(lat_lines, lon_lines)

    # Cyclic line drawing
    for line in all_lines:
        (linestyle='-', alpha=0.3, color='w')


fig = (figsize=(8, 6), edgecolor='w')
m = Basemap(projection='cyl', resolution=None,
            llcrnrlat=-90, urcrnrlat=90,
            llcrnrlon=-180, urcrnrlon=180,)

draw_map(m)
()

Well, kind of that flavor haha. You can even go ahead and print it out yourself for your little ones to learn geography.

But if he wants to learn geography, the whole world seems a bit big? Why don't we start him off by learning the locations of famous world attractions?

# Import the required packages
import numpy as np
import  as plt
from mpl_toolkits.basemap import Basemap
from itertools import chain

# The following three lines are designed to allow matplot to display Chinese characters
from pylab import mpl
['-serif'] = ['FangSong']
['axes.unicode_minus'] = False


def draw_point(m, x, y, name):
    # Here's the latitude and longitude: (longitude, latitude) #
    x, y = m(x, y)
    (x, y, 'ok', markersize=5)
    (x, y, name, fontsize=12, color="red")


def draw_map(m, scale=0.2):
    # Draw embossed images with shadows
    (scale=scale)

    # Cut according to latitude and longitude, one line for every 13 degrees
    lats = ((-90, 90, 13))
    lons = ((-180, 180, 13))

    # Collect all the lines
    lat_lines = chain(*(tup[1][0] for tup in ()))
    lon_lines = chain(*(tup[1][0] for tup in ()))
    all_lines = chain(lat_lines, lon_lines)

    # Cyclic line drawing
    for line in all_lines:
        (linestyle='-', alpha=0.3, color='w')


fig = (figsize=(8, 6), edgecolor='w')
m = Basemap(projection='cyl', resolution=None,
            llcrnrlat=-90, urcrnrlat=90,
            llcrnrlon=-180, urcrnrlon=180,)
locations = {
    'Taj Mahal': (17, 78),
    'Giza Pyramid Complex': (29, 31),
    'Stonehenge in the UK': (51, 1),
    'Notre Dame de Paris': (48, 2),
    'The Louvre': (48, 2),
    'Red Square and the Kremlin': (55, 37),
    # ...
}
draw_map(m)
for loc in locations:
    print(locations[loc])
    draw_point(m, locations[loc][1], locations[loc][0], loc)
()

Zoom in to view:

This way, just add the latitude and longitude of a location similarly to the locations and it will be displayed on the map, and you can customize it to draw a connecting line between two locations or focus on zooming in on a certain area. In short, basically anything you want to do, you can do based on Matplotlib.

to this article on the implementation of Python based on drawing your world map of the article is introduced to this, more related Python world map content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!