Skip to content

Commit 79c74ea

Browse files
author
Alfiya Tarasenko
committed
Add Python map, geocoding and reverse geocoding code samples
1 parent 931c672 commit 79c74ea

9 files changed

Lines changed: 906 additions & 1 deletion

File tree

README.md

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ Welcome to the **Geoapify Location Platform Code Samples** repository! This proj
66

77
## Available Code Samples
88

9-
### **1. Printable Route Directions (Available Now)**
9+
### **1. JavaScript: Printable Route Directions**
1010

1111
#### Description:
1212
This code sample demonstrates how to generate **Printable Route Directions** using Geoapify's Routing API and Static Maps API with JavaScript and HTML. It includes interactive features and static content generation for detailed route instructions.
@@ -24,6 +24,46 @@ This code sample demonstrates how to generate **Printable Route Directions** usi
2424
#### Demo:
2525
Explore the demo: [Printable Route Directions Demo](https://geoapify.github.io/maps-api-code-samples/javascript/printable-route-directions/demo.html)
2626

27+
28+
### **2. Python: Create Map Example**
29+
30+
#### Description:
31+
This sample demonstrates how to generate an interactive map using the Geoapify Maps API with Python and Folium.
32+
33+
#### Features:
34+
- Custom map styles using Geoapify API.
35+
- Interactive markers for enhanced user experience.
36+
- Dynamic zoom and center capabilities.
37+
38+
#### APIs Used:
39+
- [Geoapify Maps Tiles](https://www.geoapify.com/map-tiles/)
40+
41+
### **3. Python: Batch Geocode Example**
42+
43+
#### Description:
44+
This example shows how to perform forward geocoding using the Geoapify Geocoding API to obtain latitude and longitude from addresses.
45+
46+
#### Features:
47+
- Batch geocoding support.
48+
- Country filtering for improved accuracy.
49+
- NDJSON output format.
50+
51+
#### APIs Used:
52+
- [Geoapify Geocoding API](https://www.geoapify.com/geocoding-api/)
53+
54+
### **4. Python: Reverse Geocode Example**
55+
56+
#### Description:
57+
This example demonstrates how to perform reverse geocoding to retrieve addresses from latitude and longitude coordinates using the Geoapify API.
58+
59+
#### Features:
60+
- Batch processing of coordinates.
61+
- Configurable response format (`json` or `geojson`).
62+
- Country filtering for improved results.
63+
64+
#### APIs Used:
65+
- [Geoapify Reverse Geocoding API](https://www.geoapify.com/reverse-geocoding-api/)
66+
2767
---
2868

2969
## Upcoming Code Samples

javascript/.DS_Store

4 KB
Binary file not shown.

python/create-a-map/README.md

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
# Python Interactive Map Example
2+
3+
This project demonstrates how to use the [Geoapify Maps Tiles](https://www.geoapify.com/map-tiles/) to display an interactive raster map using [folium](https://pypi.org/project/folium/). The map includes customizable styles, zoom levels, and center coordinates.
4+
5+
---
6+
7+
## **Features**
8+
- Uses Geoapify Maps API for high-quality map tiles.
9+
- Supports various map styles.
10+
- Allows customization of zoom level and map center.
11+
- Displays an interactive map with an Eiffel Tower marker.
12+
- Automatically validates API keys and handles errors.
13+
14+
![Route Preview on a Map](https://github.com/geoapify/maps-api-code-samples/blob/main/python/create-a-map/map.png?raw=true)
15+
16+
## **Requirements**
17+
18+
Ensure you have the following installed:
19+
20+
1. Python 3.11 or higher
21+
2. pip (Python package manager)
22+
23+
## **Setup Instructions**
24+
25+
### 1. Clone the Repository
26+
27+
```bash
28+
git clone https://geoapify.github.io/maps-api-code-samples/
29+
cd maps-api-code-samples/python
30+
```
31+
32+
### 2. Create a Virtual Environment (Optional)
33+
34+
It’s recommended to use a virtual environment to avoid dependency conflicts:
35+
36+
```bash
37+
python -m venv env
38+
source env/bin/activate # On Windows: env\Scripts\activate
39+
```
40+
41+
### 3. Install Dependencies
42+
43+
Install the required Python libraries using pip:
44+
45+
```bash
46+
pip install folium requests
47+
```
48+
49+
---
50+
51+
## **Running the Example**
52+
53+
Run the script to generate an interactive map:
54+
55+
```bash
56+
cd create-a-map
57+
python interactive_map.py --style osm-bright --zoom 12 --lat 48.8566 --lon 2.3522 --api-key=YOUR_API_KEY
58+
```
59+
60+
### **Command-line Arguments**
61+
- `--api-key` (required): API key for Geoapify services.
62+
- `--style` (optional, default: `osm-carto`): Map style.
63+
- `--zoom` (optional, default: `17`): Zoom level.
64+
- `--lat` (optional, default: `48.8584`): Latitude for the map center.
65+
- `--lon` (optional, default: `2.2945`): Longitude for the map center.
66+
67+
---
68+
69+
## Code Explanation
70+
71+
The `create_map` function initializes an interactive map using `folium`. It takes the map style, zoom level, latitude, longitude, and API key as parameters to generate a customized map with Geoapify tiles.
72+
73+
```python
74+
import folium
75+
76+
BASE_URL = "https://maps.geoapify.com/v1/tile/{map_style}/{{z}}/{{x}}/{{y}}@2x.png?apiKey={api_key}"
77+
78+
def create_map(map_style, zoom, lat, lon, api_key):
79+
"""
80+
Creates an interactive map using Geoapify tiles.
81+
82+
Parameters:
83+
- map_style (str): The style of the map (e.g., 'osm-carto', 'osm-bright').
84+
- zoom (int): The initial zoom level.
85+
- lat (float): Latitude for the map center.
86+
- lon (float): Longitude for the map center.
87+
- api_key (str): API key for accessing Geoapify services.
88+
89+
Returns:
90+
- folium.Map object containing the configured map.
91+
"""
92+
93+
# Initialize the folium map centered at the specified location
94+
m = folium.Map(location=[lat, lon], zoom_start=zoom)
95+
96+
# Construct the tile layer URL using the provided API key and map style
97+
tile_url = BASE_URL.format(map_style=map_style, api_key=api_key)
98+
99+
# Add Geoapify tile layer to the map
100+
folium.TileLayer(
101+
tiles=tile_url,
102+
name="Geoapify Map",
103+
attr="""Powered by <a href="https://www.geoapify.com/" target="_blank">Geoapify</a>
104+
| <a href="https://openmaptiles.org/" rel="nofollow" target="_blank">© OpenMapTiles</a>
105+
| <a href="https://www.openstreetmap.org/copyright" rel="nofollow" target="_blank">© OpenStreetMap</a> contributors""",
106+
overlay=True,
107+
control=True
108+
).add_to(m)
109+
110+
# Add a marker at the Eiffel Tower location for demonstration purposes
111+
folium.Marker(
112+
location=[48.8584, 2.2945],
113+
popup="Eiffel Tower",
114+
icon=folium.Icon(color="red"),
115+
).add_to(m)
116+
117+
return m
118+
```
119+
120+
### **Explanation**
121+
1. **Initialize the Map**
122+
- Uses `folium.Map()` to create a base map centered at the provided latitude and longitude.
123+
- The `zoom_start` parameter determines the initial zoom level.
124+
125+
2. **Add Tile Layer**
126+
- The tile layer URL is formatted using the provided `map_style` and `api_key` values.
127+
- The tile layer is added using `folium.TileLayer()`, ensuring that Geoapify map styles are applied.
128+
129+
3. **Add a Marker**
130+
- A red marker is placed at the Eiffel Tower's coordinates (`48.8584, 2.2945`).
131+
- The marker has a popup message that appears when clicked.
132+
133+
4. **Return the Map**
134+
- The function returns a `folium.Map` object that can be saved as an HTML file or displayed in a browser.
135+
136+
This function allows users to create a customizable interactive map with Geoapify tiles, supporting different styles and zoom levels.
137+
138+
---
139+
140+
## **Output**
141+
- The script generates a `map.html` file.
142+
- The browser automatically opens the generated map.
143+
- If the browser fails to open, manually open `map.html` in any web browser.
144+
145+
## **Error Handling**
146+
- If an invalid map style is provided, the script falls back to `osm-carto`.
147+
- If an invalid API key is provided, the script exits with an error.
148+
- If a server error occurs (5XX response), the script stops execution.
149+
150+
## **Notes**
151+
- Ensure that you have a valid [Geoapify API key](https://www.geoapify.com/) before running the script.
152+
- The map includes attribution links to comply with OpenStreetMap and Geoapify usage policies.
153+
154+
## **License**
155+
This project is licensed under the MIT License.
156+
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
"""
2+
This script generates an interactive map using the Geoapify Maps API and displays it in a web browser using folium.
3+
4+
Dependencies:
5+
- folium
6+
- requests
7+
8+
To install the required libraries, run:
9+
pip install folium requests
10+
11+
Usage:
12+
python interactive_map.py --style osm-bright --zoom 12 --lat 48.8566 --lon 2.3522 --api-key=your-api-key
13+
14+
Command-line arguments:
15+
--api-key: Api Key for Geoapify services
16+
--style: Map style (default: osm-carto)
17+
--zoom: Zoom level (default: 17)
18+
--lat: Latitude for the map center (default: 48.8584)
19+
--lon: Longitude for the map center (default: 2.2945)
20+
"""
21+
22+
import argparse
23+
import sys
24+
import webbrowser
25+
26+
import folium
27+
import requests
28+
29+
# Define base URL for Geoapify
30+
BASE_URL = "https://maps.geoapify.com/v1/tile/{map_style}/{{z}}/{{x}}/{{y}}@2x.png?apiKey={api_key}"
31+
32+
33+
def create_map(map_style, zoom, lat, lon, api_key) -> folium.Map:
34+
# Create a folium map centered at the given latitude and longitude
35+
m = folium.Map(location=[lat, lon], zoom_start=zoom)
36+
37+
# Construct the tile URL with the selected map style and API Key
38+
tile_url = BASE_URL.format(map_style=map_style, api_key=api_key)
39+
40+
# Add the Geoapify raster tiles to the map
41+
folium.TileLayer(
42+
tiles=tile_url,
43+
name='Geoapify Map',
44+
attr="""Powered by <a href="https://www.geoapify.com/" target="_blank">Geoapify</a>
45+
| <a href="https://openmaptiles.org/" rel="nofollow" target="_blank">© OpenMapTiles</a>
46+
<a href="https://www.openstreetmap.org/copyright" rel="nofollow" target="_blank">© OpenStreetMap</a> contributors""",
47+
overlay=True,
48+
control=True
49+
).add_to(m)
50+
51+
# Add Eiffel Tower pin to the map
52+
folium.Marker(
53+
location=[48.8584, 2.2945],
54+
popup='Eiffel Tower',
55+
icon=folium.Icon(color='red'),
56+
).add_to(m)
57+
58+
# Return the map object
59+
return m
60+
61+
62+
def get_arg_parser() -> argparse.ArgumentParser:
63+
parser = argparse.ArgumentParser(description='Generate an interactive map using Geoapify Maps API.')
64+
parser.add_argument('--style', type=str, default='osm-carto', help='Map style (default: osm-carto)')
65+
parser.add_argument('--zoom', type=int, default=17, help='Zoom level (default: 17)')
66+
parser.add_argument('--lat', type=float, default=48.8584, help='Latitude for the map center (default: 48.8584)')
67+
parser.add_argument('--lon', type=float, default=2.2945, help='Longitude for the map center (default: 2.2945)')
68+
parser.add_argument('--api-key', type=str, required=True, help='Api Key for Geoapify services')
69+
70+
return parser
71+
72+
73+
def main():
74+
# Set up argument parsing for command-line customization
75+
parser = get_arg_parser()
76+
args = parser.parse_args()
77+
78+
# Validate the map style by making a request to the Geoapify API
79+
response = requests.get(BASE_URL.format(map_style=args.style,
80+
api_key=args.api_key).replace('{z}/{x}/{y}', '0/0/0'))
81+
if response.status_code == 400:
82+
print(f"Error: Possible issue with incorrect map style. Falling back to default 'osm-carto'.")
83+
args.style = 'osm-carto'
84+
elif response.status_code == 401:
85+
print('Invalid Api Key, abort')
86+
sys.exit(1)
87+
elif response.status_code // 100 == 5:
88+
print('Server respond with 5XX error, abort')
89+
sys.exit(1)
90+
91+
# Create the map with the specified parameters
92+
map_object = create_map(args.style, args.zoom, args.lat, args.lon, args.api_key)
93+
94+
# Better not to use show_in_browser method as it can lead to file not found error in different os
95+
map_object.save('map.html')
96+
if not webbrowser.open('map.html'):
97+
print('Cannot open default browser, check your settings')
98+
99+
100+
if __name__ == "__main__":
101+
main()

python/create-a-map/map.png

1.48 MB
Loading

0 commit comments

Comments
 (0)