文章目录
- 1、前言
- 2、Flask测试网页(GIS地图)
- 2.1 基于model-viewer的太阳系查看的网页
- 2.2 基于openlayers的在线地图叠加geojson的网页
- 2.3 基于openlayers的离线地图瓦片的网页
- 2.4 基于leaflet的在线地图叠加mbtiles的网页
- 2.5 基于cesium.js的三维地球显示的网页
- 结语
1、前言
提示:Flask是一个用python语言基于Werkzeug工具箱编写的轻量级web开发框架,它主要面向需求简单,项目周期短的小应用。
Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 。Flask使用 BSD 授权。
Flask也被称为 “microframework” ,因为它使用简单的核心,用 extension 增加其他功能。Flask没有默认使用的数据库、窗体验证工具。
2、Flask测试网页(GIS地图)
2.1 基于model-viewer的太阳系查看的网页
该例子的具体介绍请见作者的另一篇文章,网址如下:
【小沐科普】小沐带您遨游太阳系(model-viewer,trimesh,Python)
这里通过编写python代码,搭建flask的web服务器环境,运行这个网页例子。
- test_solarsystem.py:
#***************************************************************
# Purpose: 基于model-viewer的太阳系查看的网页(Flask的web服务器)
# Author: 爱看书的小沐
# Date: 2022-5-8
# Languages: python
# Platform: python 3.9 win64
# OS: Win10 win64
# **************************************************************
from flask import Flask, redirect, url_for, request, render_template, Response
from io import FileIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('solar_system.html')
@app.route("/images/<filename>")
def get_image(filename):
with open("static/images/{}".format(filename), 'rb') as f:
image = f.read()
resp = Response(image, mimetype="image/jpg")
return resp
@app.route("/glb/<filename>")
def get_binary(filename):
data = FileIO("static/glb/{}".format(filename))
resp = Response(data, mimetype="application/zip")
return resp
if __name__ == '__main__':
app.run(debug = True)
2.2 基于openlayers的在线地图叠加geojson的网页
该例子的具体介绍请见作者的另一篇文章,网址如下:
【GIS开发】OpenLayers入门学习(JavaScript库)
- test_openlayers.py:
#***************************************************************
# Purpose: 基于openlayers的在线地图叠加geojson的网页(Flask的web服务器)
# Author: 爱看书的小沐
# Date: 2022-5-8
# Languages: python
# Platform: python 3.9 win64
# OS: Win10 win64
# **************************************************************
from flask import Flask, Response, request
from flask import render_template, make_response, jsonify, send_from_directory,redirect, url_for
from io import FileIO
import os
import mimetypes
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
# CORS(app, supports_credentials=True)
# CORS(app, resources=r'/*')
# CORS(app, resources={r'/*': {'origins': '*'}})
# cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
app = Flask(__name__)
@app.route('/')
def index():
return render_template('test_openlayers.html')
# return render_template('test_openlayers2_offlinemap.html')
def get_localfile(directory, path):
response = make_response(send_from_directory(directory, path.encode('utf-8').decode('utf-8'), as_attachment=False))
mime_type = mimetypes.guess_type(path)[0]
if path.endswith(".js") :
mime_type = "application/javascript"
response.headers['Content-Type'] = mime_type
print(directory, path, mime_type)
return response
@app.route("/<path:path>")
def get_staticfile(path):
directory = os.getcwd() + "/static/"
return get_localfile(directory, path)
@app.route("/tile/<path:path>")
def get_tilefile(path):
directory = "D:/test/maps/"
return get_localfile(directory, path)
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico'
, mimetype='image/vnd.microsoft.icon')
if __name__ == '__main__':
app.run(debug = True)
- test_openlayers.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/css/ol.css" type="text/css">
<style>.map {
height: 45rem;
width: 100%;
}</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/build/ol.js"></script>
<title>OpenLayers example</title>
</head>
<body>
<h2>爱看书的小沐的地图</h2>
<div id="map" class="map"></div>
<script type="text/javascript">var pointGeoJsonLayer = new ol.layer.Vector({
title: 'points',
source: new ol.source.Vector({
projection: 'EPSG:4326',
url: 'json/china.json',
format: new ol.format.GeoJSON()
})
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
pointGeoJsonLayer
],
view: new ol.View({
center: ol.proj.fromLonLat([104.1, 21.6]),
zoom: 3
})
});</script>
</body>
</html>
运行结果如下:
2.3 基于openlayers的离线地图瓦片的网页
test_openlayers.py: 和2.2 基于openlayers的在线地图叠加geojson的网页相同。
- test_openlayers.html:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>本地瓦片数据测试</title>
<link rel="stylesheet" href="/openlayers/v6.13.0-dist/ol.css" />
<style>body, html {
width: 100%;
height: 100%;
}
#map, #info {
width: 100%;
height: 100%;
}</style>
<script src="/openlayers/v6.13.0-dist/ol.js"></script>
</head>
<body>
<div id="map"></div>
<script type="text/javascript">var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: "http://127.0.0.1:5000/tile/{z}/{x}/{y}.png",
attributions: "test"
})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
}),
controls: ol.control.defaults().extend([
new ol.control.FullScreen(),
new ol.control.MousePosition(),
new ol.control.OverviewMap(),
new ol.control.ScaleLine(),
new ol.control.ZoomSlider(),
new ol.control.ZoomToExtent()
]),
});</script>
</body>
</html>
运行结果如下:
2.4 基于leaflet的在线地图叠加mbtiles的网页
该例子的具体介绍请见作者的另一篇文章,网址如下:
【GIS开发】Leaflet入门学习(Javascript库)
- test_leaflet.py:
#***************************************************************
# Purpose: 基于leaflet的在线地图叠加mbtiles的网页(Flask的web服务器)
# Author: 爱看书的小沐
# Date: 2022-5-8
# Languages: python
# Platform: python 3.9 win64
# OS: Win10 win64
# **************************************************************
from flask import Flask, redirect, url_for, request, render_template, Response
from io import FileIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('test_leaflet.html')
@app.route("/json/<filename>")
def get_binary(filename):
data = FileIO("static/json/{}".format(filename))
resp = Response(data, mimetype="application/json")
return resp
@app.route("/js/<filename>")
def get_js(filename):
data = FileIO("static/js/{}".format(filename))
resp = Response(data, mimetype="application/html")
return resp
if __name__ == '__main__':
app.run(debug = True)
- test_leaflet.html:
<!DOCTYPE html>
<html>
<head>
<title>Leaflet sample</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin="" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin="" ></script>
<!-- https://gitlab.com/IvanSanchez/Leaflet.TileLayer.MBTiles -->>
<script src="js/Leaflet.TileLayer.MBTiles.js"></script>
<script src="https://unpkg.com/sql.js@0.3.2/js/sql.js"></script>
</head>
<body>
<div id="map" style="width: 900px; height:"></div>
<script>var map = new L.Map('map').fitWorld();
var mb = L.tileLayer.mbTiles('json/world_countries.mbtiles').addTo(map);
mb.on('databaseloaded', function(ev) {
console.info('MBTiles DB loaded', ev);
});
mb.on('databaseerror', function(ev) {
console.info('MBTiles DB error', ev);
});</script>
</body>
</html>
运行结果如下
2.5 基于cesium.js的三维地球显示的网页
Cesium是国外一个基于JavaScript编写的使用WebGL的地图引擎。Cesium支持3D,2D,2.5D形式的地图展示。它提供了基于JavaScript语言的开发包,方便用户快速搭建一款零插件的虚拟地球Web应用,并在性能,精度,渲染质量以及多平台,易用性上都有高质量的保证。
test_cesiumjs.py:
from flask import Flask, Response
from flask import render_template, make_response, jsonify, send_from_directory
from io import FileIO
import os
import mimetypes
app = Flask(__name__)
@app.route('/')
def index():
return render_template('test_cesium3.html')
@app.route("/Cesium-1.93/Build/Cesium/<path:path>")
def get_cesiumfile(path):
directory = os.getcwd() + "/static/Cesium-1.93/Build/Cesium/"
response = make_response(send_from_directory(directory, path.encode('utf-8').decode('utf-8'), as_attachment=False))
mime_type = mimetypes.guess_type(path)[0]
if path.endswith(".js") :
mime_type = "application/javascript"
response.headers['Content-Type'] = mime_type
print(directory, path, mime_type)
return response
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico'
, mimetype='image/vnd.microsoft.icon')
if __name__ == '__main__':
app.run(debug = True)
- test_cesiumjs.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>cesium.js example</title>
<meta charset="utf-8">
<!-- Include the CesiumJS JavaScript and CSS files -->
<script src="Cesium-1.93/Build/Cesium/Cesium.js"></script>
<link href="Cesium-1.93/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
</head>
<body>
<div id="cesiumContainer"></div>
<script>// Your access token can be found at: https://cesium.com/ion/tokens.
// This is the default access token from your ion account
Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3ZGQ4ZTc1Yy0xZjY1LTQzYzUtYjhiZi1iYTliZWFkZTVhMjYiLCJpZCI6ODc4MjQsImlhdCI6MTY0ODcyMTAyNH0.hL34d0emYTYCqDlmTq8lpL4UyA_p6W4BOATX9JqDHQs';
// Initialize the Cesium Viewer in the HTML element with the `cesiumContainer` ID.
const viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider: Cesium.createWorldTerrain()
});
// Add Cesium OSM Buildings, a global 3D buildings layer.
const buildingTileset = viewer.scene.primitives.add(Cesium.createOsmBuildings());
// Fly the camera to San Francisco at the given longitude, latitude, and height.
viewer.camera.flyTo({
destination : Cesium.Cartesian3.fromDegrees(-122.4175, 37.655, 400),
orientation : {
heading : Cesium.Math.toRadians(0.0),
pitch : Cesium.Math.toRadians(-15.0),
}
});</script>
</div>
</body>
</html>
- 运行结果:
结语
如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;
╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;
o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;
(✿◡‿◡)
感谢各位童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!