create a website that is able to cache google maps images and show them from a locally…
- User
create a website that is able to cache google maps images and show them from a locally hosted instead of accessing them from the web
Assistant
create a website that is able to cache google maps images and show them from a locally hosted instead of accessing them from the web
This project will create a local web server that acts as a proxy for Google Maps tile images. When your browser requests a map tile, the server will first check if it has a cached copy. If not, it will fetch the tile from Google Maps, save it locally, and then serve it to your browser. Subsequent requests for the same tile will be served from your local cache, reducing external API calls and potentially improving load times after the initial fetch.
Important Disclaimer:
Directly accessing Google Maps tile servers (https://{s}.google.com/vt/lyrs=...) without using the official Google Maps JavaScript API or Static Maps API is against Google's Terms of Service for production applications. This project is intended for educational and demonstration purposes only to illustrate caching mechanisms. For any production application, you should use the official Google Maps APIs, which require an API key and adherence to their usage policies.
google-maps-cache/
├── app.py
├── templates/
│ └── index.html
└── cache/ (This directory will be created automatically)
Create a Project Directory:
mkdir google-maps-cache
cd google-maps-cache
Create a Virtual Environment (Recommended):
python -m venv venv
Activate the Virtual Environment:
.\venv\Scripts\activatesource venv/bin/activateInstall Dependencies:
We'll use Flask for the web server and requests to fetch images from Google.
pip install Flask requests
app.py)This Python script will handle requests for map tiles, manage the cache, and serve the index.html file.
Create a file named app.py in the google-maps-cache directory:
import os
import requests
from flask import Flask, send_file, render_template, abort
app = Flask(__name__)
# --- Configuration ---
CACHE_DIR = 'cache'
# Ensure the cache directory exists
os.makedirs(CACHE_DIR, exist_ok=True)
# Google Maps tile URL template (roadmap tiles 'm')
# 's' is the subdomain, x, y, z are tile coordinates
# Note: Using these direct tile URLs is for demonstration ONLY and bypasses Google's TOS for production.
GOOGLE_MAPS_TILE_URL_TEMPLATE = "https://{s}.google.com/vt/lyrs={map_type}&x={x}&y={y}&z={z}"
TILE_SUBDOMAINS = ['mt0', 'mt1', 'mt2', 'mt3'] # Google uses multiple subdomains
DEFAULT_MAP_TYPE = 'm' # 'm' for roadmap, 's' for satellite, 'p' for terrain
@app.route('/')
def index():
"""Serves the main HTML page with the map."""
return render_template('index.html')
@app.route('/tiles/<map_type>/<int:z>/<int:x>/<int:y>')
def serve_map_tile(map_type, z, x, y):
"""
Serves map tiles from cache or fetches them from Google Maps.
Args:
map_type (str): Type of map ('m' for roadmap, 's' for satellite, etc.)
z (int): Zoom level
x (int): X-coordinate of the tile
y (int): Y-coordinate of the tile
"""
if map_type not in ['m', 's', 'p', 't', 'r', 'h']: # Basic validation of map_type
abort(404, description="Invalid map type")
# Construct the path for the cached tile
# Example: cache/m/10/500/300.png
tile_cache_path = os.path.join(CACHE_DIR, map_type, str(z), str(x), f"{y}.png")
# Check if the tile is already in cache
if os.path.exists(tile_cache_path):
print(f"Serving from cache: {tile_cache_path}")
return send_file(tile_cache_path, mimetype='image/png')
else:
print(f"Fetching from Google: {map_type}/{z}/{x}/{y}")
# Select a subdomain for the request
subdomain = TILE_SUBDOMAINS[(x + y) % len(TILE_SUBDOMAINS)]
# Construct the Google Maps URL
google_url = GOOGLE_MAPS_TILE_URL_TEMPLATE.format(
s=subdomain, map_type=map_type, x=x, y=y, z=z
)
try:
# Fetch the tile from Google Maps
response = requests.get(google_url, stream=True, timeout=5)
response.raise_for_status() # Raise an exception for bad status codes
# Ensure the directory structure exists for the cached tile
os.makedirs(os.path.dirname(tile_cache_path), exist_ok=True)
# Save the tile to cache
with open(tile_cache_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Cached and serving: {tile_cache_path}")
return send_file(tile_cache_path, mimetype='image/png')
except requests.exceptions.RequestException as e:
print(f"Error fetching tile {google_url}: {e}")
abort(500, description=f"Could not fetch tile: {e}")
if __name__ == '__main__':
# Run the Flask app in debug mode (auto-reloads on code changes)
# In production, use a production-ready WSGI server like Gunicorn or uWSGI
app.run(debug=True, port=5000)
templates/index.html)This HTML file will use the Leaflet.js library to display the map and request tiles from your local Flask server.
Create a directory named templates inside google-maps-cache, and then create a file named index.html inside the templates directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cached Google Maps</title>
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzxHlY/yykJyLvSsTjSyj91qQo="
crossorigin=""/>
<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJN7kXAkaHPgM7+NDQkS51owH9byY="
crossorigin=""></script>
<style>
#map {
height: 100vh; /* Make the map fill the viewport height */
width: 100%; /* Make the map fill the viewport width */
margin: 0;
padding: 0;
}
body {
margin: 0;
padding: 0;
overflow: hidden; /* Prevent scrollbars if map fills viewport */
}
.controls {
position: absolute;
top: 10px;
left: 10px;
background: white;
padding: 10px;
border-radius: 5px;
z-index: 1000; /* Ensure controls are above the map */
}
</style>
</head>
<body>
<div id="map"></div>
<div class="controls">
<label for="mapType">Map Type:</label>
<select id="mapType" onchange="changeMapType()">
<option value="m" selected>Roadmap</option>
<option value="s">Satellite</option>
<option value="p">Terrain</option>
<option value="t">Topographic</option>
<option value="r">Streetview Road Overlay</option>
<option value="h">Roadmap (only roads and features)</option>
</select>
</div>
<script>
// Default map type
let currentMapType = 'm';
// Initialize the map
const map = L.map('map').setView([34.0522, -118.2437], 13); // Centered on Los Angeles
// Create a tile layer pointing to your Flask backend
let tileLayer = L.tileLayer(`/tiles/${currentMapType}/{z}/{x}/{y}`, {
maxZoom: 20,
minZoom: 1,
attribution: 'Map data © <a href="https://www.google.com/maps/">Google Maps</a> | Powered by <a href="http://leafletjs.com/">Leaflet</a> | Cached by Local Server'
}).addTo(map);
function changeMapType() {
const selectElement = document.getElementById('mapType');
const newMapType = selectElement.value;
if (newMapType !== currentMapType) {
currentMapType = newMapType;
// Remove the old tile layer
map.removeLayer(tileLayer);
// Create and add the new tile layer
tileLayer = L.tileLayer(`/tiles/${currentMapType}/{z}/{x}/{y}`, {
maxZoom: 20,
minZoom: 1,
attribution: 'Map data © <a href="https://www.google.com/maps/">Google Maps</a> | Powered by <a href="http://leafletjs.com/">Leaflet</a> | Cached by Local Server'
}).addTo(map);
}
}
</script>
</body>
</html>
Open your terminal and navigate to the google-maps-cache directory.
Activate your virtual environment (if you created one).
.\venv\Scripts\activatesource venv/bin/activateRun the Flask application:
python app.py
You should see output similar to:
* Serving Flask app 'app'
* Debug mode: on
INFO:werkzeug:WARNING: This is a development server. Do not use it in a production deployment.
INFO:werkzeug:WARNING: Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
INFO:werkzeug:Debugger PIN: ...
Open your web browser and go to http://127.0.0.1:5000 (or http://localhost:5000).
When you first open the map or pan/zoom to an area, look at your terminal where app.py is running. You'll see messages like:
Fetching from Google: m/13/1310/3180
Cached and serving: cache/m/13/1310/3180.png
This indicates the server fetched the tile from Google, saved it, and served it to your browser.
Now, pan or zoom back to an area you've already viewed. You'll see messages like:
Serving from cache: cache/m/13/1310/3180.png
This confirms the tile was loaded directly from your local cache/ directory, without making another request to Google.
Explore the google-maps-cache/cache/ directory. You'll find subdirectories for map_type/zoom_level/x_coordinate/y_coordinate.png (e.g., cache/m/13/1310/3180.png) containing the downloaded image files.
If you want to clear all cached images, simply delete the cache directory:
rm -rf cache # On macOS/Linux
rmdir /s /q cache # On Windows (from command prompt)
Then restart the app.py script. The next time you access the map, all tiles will be fetched from Google again.
This setup provides a functional demonstration of caching Google Maps tiles locally. Remember the important disclaimer regarding Google's Terms of Service for production use.