flask+leaflet
时间: 2023-08-26 14:07:04 浏览: 145
flask
Flask is a popular Python web framework that allows you to build web applications quickly and easily. Leaflet is an open-source JavaScript library for interactive maps.
To use Leaflet with Flask, you need to:
1. Install Flask and Leaflet: You can install Flask using pip and Leaflet using npm.
2. Create a Flask application: Create a new Flask application using the Flask CLI or by creating a new Python file.
3. Create a template: Create a new HTML template to display your Leaflet map.
4. Add Leaflet to your template: Add the Leaflet CSS and JS files to your template.
5. Create a map: Use Leaflet to create a new map and add it to your template.
6. Serve your application: Run your Flask application and navigate to the URL to view your map.
Here's an example of how to create a simple Leaflet map in Flask:
```
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
```
In this example, we create a new Flask application and define a route for the index page. We then create a new HTML template called `index.html` and render it when the index route is accessed.
Here's what the `index.html` file might look like:
```
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Map</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha384-3e3q5O9Xrj+61R1JZ5p5Obl7J5w1KgJ8xQzHq3V5X9gMf5R5f5TE5B5V7nDwCKj/" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha384-iLhD8xj1Tz0iY9Xh+FXJjMwnA91dZvO4oFw4G4fRbnzKj77yUJh6AneS6UdtN2Ua" crossorigin=""></script>
</head>
<body>
<div id="map" style="height: 500px;"></div>
<script>
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'your.mapbox.access.token'
}).addTo(map);
</script>
</body>
</html>
```
In this template, we include the Leaflet CSS and JS files and create a new map using the Leaflet library. We then add a tile layer from Mapbox and set the initial view of the map to London.
When you run this Flask application and navigate to the index page, you should see a Leaflet map displayed in your browser.
阅读全文