我正在尝试从文本框中输入用户的家庭住址,对地址进行地址编码,然后将数据加载到传单地图上。我正在获取正确的纬度和经度,并且它按预期显示在我的html模板上。但是,如果我尝试将python数据传递给JavsScript,则不会加载数据。不知道我是否正确解释了这一点;我是编程新手。这是我的代码:
HTML索引
<!DOCTYPE html>
<html>
<head>
<title>Examples</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h1>enter your address</h1>
<form method="POST" action="/">
<div class="form-group">
<input type="text" name="address">
</div>
<input class="btn btn-primary" type="submit" value="submit">
</form>
</body>
</html>
点击按钮后加载的HTML模板
<!DOCTYPE html>
<html>
<head>
<title>Examples</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
<link rel="stylesheet" href="static/style.css">
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="static/map.js"></script>
</head>
<body>
<h1>address is {{ userlat, userlng }}</h1>
<div id="map"></div>
</body>
</html>
Python / Flask文件
from flask import Flask, render_template, request
from geopy.geocoders import GoogleV3
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
address = request.form['address']
geolocator = GoogleV3()
location = geolocator.geocode(address)
userlat = location.latitude
userlng = location.longitude
return render_template('address.html', userlat=userlat, userlng=userlng)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
传单地图
window.onload = function () {
var maplat = '{{ userlat }}'
var mapltd = '{{ userltd }}'
var map = L.map('map').setView([47.60, -122.33], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.marker([maplat, mapltd]).addTo(map)
.bindPopup('your address')
.openPopup();
};
我确定这与var maplat ='{{userlat}}'和var mapltd ='{{userltd}}'有关,但我似乎无法弄清楚。谢谢!
编辑:我忘了补充一点,我在控制台“ Invalid LatLng object:({{userlat}},{{userltd}})中收到错误