
144 views
Plotting Google Map using gmplot package in Python
The plot Google Maps using the gmplot
package in Python, you’ll need to follow these steps:
- Install the
gmplot
package: You can installgmplot
using pip:
pip install gmplot
- Import the necessary modules and set up your Google Maps API key: You’ll need a Google Maps API key to use the
gmplot
library. You can obtain an API key from the Google Cloud Console (https://console.cloud.google.com/). Make sure to enable the “Maps JavaScript API” for your project. Once you have your API key, you can use it in your Python script:
import gmplot
# Replace 'YOUR_API_KEY' with your actual API key
gmap = gmplot.GoogleMapPlotter.from_geocode("YOUR_API_KEY")
- Add markers, shapes, or paths to your map: You can add various elements to your Google Map using
gmplot
. Here are a few examples:
- Adding a marker:
gmap.marker(37.7749, -122.4194, title="San Francisco")
- Adding a shape (polygon):
lats = [37.773972, 37.774546, 37.773972] lngs = [-122.419806, -122.419006, -122.418206] gmap.polygon(lats, lngs, color="cornflowerblue")
- Adding a path (line):
path_lats = [37.7749, 37.773972, 37.774546] path_lngs = [-122.4194, -122.419806, -122.419006] gmap.plot(path_lats, path_lngs, "red", edge_width=3)
- Save the map to an HTML file: After adding the desired elements to your map, you can save it to an HTML file for viewing in a web browser:
gmap.draw("mymap.html")
Here’s a complete example that creates a simple Google Map with a marker, a shape, and a path:
import gmplot
# Replace 'YOUR_API_KEY' with your actual API key
gmap = gmplot.GoogleMapPlotter.from_geocode("YOUR_API_KEY")
# Add a marker for San Francisco
gmap.marker(37.7749, -122.4194, title="San Francisco")
# Add a polygon (shape)
lats = [37.773972, 37.774546, 37.773972]
lngs = [-122.419806, -122.419006, -122.418206]
gmap.polygon(lats, lngs, color="cornflowerblue")
# Add a path (line)
path_lats = [37.7749, 37.773972, 37.774546]
path_lngs = [-122.4194, -122.419806, -122.419006]
gmap.plot(path_lats, path_lngs, "red", edge_width=3)
# Save the map to an HTML file
gmap.draw("mymap.html")
Running this script will generate an HTML file (“mymap.html”) that you can open in a web browser to view your Google Map with markers, shapes, and paths.