Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Vẽ Google Map với package gmplot trong Python

Có nhiều cách vẽ tọa độ địa lý trên Google Maps. Muốn lưu vào file local, cách tốt là dùng module Python gmplot.

Thư viện gmplot cho phép vẽ dữ liệu lên Google Maps. Gmplot có interface như matplotlib để sinh HTML và javascript hiển thị dữ liệu trên Google Maps.

Cài đặt

pip install gmplot

gmplot có nhiều phương thức vẽ để tạo bản đồ khám phá đơn giản. Rất linh hoạt, có thể sinh HTML trực tiếp.

Trường hợp 1: Tạo base map với gmplot

Đặt bản đồ tại vị trí cụ thể: cần latitude, longitude và zoom resolution.


from gmplot import *
gmap = gmplot.GoogleMapPlotter(17.438139, 78.39583, 18)
gmap.draw("C:\\Users\\rajesh\\Desktop\\map11.html")

Lưu ý: Google Maps API không còn miễn phí. Cần thêm API_KEY để xem bản đồ đầy đủ. Code thêm API key:


gmap = gmplot.GoogleMapPlotter(17.438139, 78.3936413, 18)
gmap.apikey = "AIzaSyDeRNMnZ__VnQDiATiuz4kPjF_c9r1kWe8"
gmap.draw("C:\\Users\\rajesh\\Desktop\\map11.html")

Lấy API key tại: https://developers.google.com/maps/documentation/embed/get-api-key

Trường hợp 2: Vẽ polygon (đa giác) trên Google Map


import gmplot
latitude_list = [17.4567417, 17.5587901, 17.6245545]
longitude_list = [78.2913637, 78.007699, 77.9266135]
gmap = gmplot.GoogleMapPlotter(17.438139, 78.3936413, 11)
gmap.scatter(latitude_list, longitude_list, '#FF0000', size=40, marker=False)
gmap.polygon(latitude_list, longitude_list, color='cornflowerblue')
gmap.apikey = "Your_API_KEY"
gmap.draw("C:\\Users\\rajesh\\Desktop\\map3.html")

Trường hợp 3: Scatter points và vẽ đường nối giữa các tọa độ


import gmplot
Charminar_top_attraction_lats, Charminar_top_attraction_lons = zip(*[
    (17.3833, 78.4011), (17.4239, 78.4738), (17.3713, 78.4804), (17.3616, 78.4747),
    (17.3578, 78.4717), (17.3604, 78.4736), (17.2543, 78.6808), (17.4062, 78.4691),
    (17.3950, 78.3968), (17.3587, 78.2988), (17.4156, 78.4750)
])
gmap3 = gmplot.GoogleMapPlotter(17.3616, 78.4747, 13)
gmap3.scatter(Charminar_top_attraction_lats, Charminar_top_attraction_lons, '#FF0000', size=50, marker=False)
gmap3.plot(Charminar_top_attraction_lats, Charminar_top_attraction_lons, 'cornflowerblue', edge_width=3.0)
gmap3.apikey = "API_Key"
gmap3.draw(r"c:\users\rajesh\desktop\maps\scatter.html")

Trường hợp 4: Heatmap và scatter trong một biểu đồ (biểu diễn động đất)


import gmplot
import numpy as np
latitude = (np.random.random_sample(size=700) - 0.5) * 180
longitude = (np.random.random_sample(size=700) - 0.5) * 360
gmap = gmplot.GoogleMapPlotter(0, 0, 2)
gmap.heatmap(latitude, longitude)
gmap.scatter(latitude, longitude, c='r', marker=True)
gmap.apikey = "Your_Google_API_Key"
gmap.draw(r"c:\users\rajesh\desktop\maps\country_heatmap.html")