javascript - 使用 javascript 变量设置 img src 以在 Google Maps InfoWindow 中使用
问题描述
我正在尝试打开 Google Maps InfoWindow 以显示图像,但我想使用 javascript 变量定义图像源。
这是我使用 Flask 的 Python 代码。
import os
from flask import Flask, render_template
from flask_jsglue import JSGlue
# Start the Flask application
app = Flask(__name__)
jsglue = JSGlue(app)
# Get the Google Maps API key from the file
with open(os.getcwd() + '/data/GoogleMapsAPIkey.txt') as f:
APIkey = f.readline()
f.close
app.config['API_KEY'] = APIkey
@app.route('/')
def index():
return render_template('./test.html', key=APIkey)
if __name__ == '__main__':
app.run(debug=False)
这是我正在使用的 HTML。
<!DOCTYPE html>
<html>
<head>
<title>Thumb in window test</title>
{{ JSGlue.include() }}
<meta charset="utf-8">
<style>
#map-canvas {
width: 100%;
height: 500px;
}
</style>
</head>
<body>
<div id="map-canvas">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var map;
var thumbWindow;
function showMap(){
// Create the map
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: -37.8135, lng: 144.9655},
zoom: 14
});
google.maps.event.addDomListener(map, 'click', showThumb);
}
function showThumb(){
thumbWindow = new google.maps.InfoWindow();
thumbWindow.setContent('<img id="thumb" src="/static/thumbs/2_thumb.JPG" align="middle">');
thumbWindow.setPosition(map.getCenter());
thumbWindow.open(map);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key={{ key }}&callback=showMap">
</script>
</body>
</html>
这一切都按预期工作,但前提是我在 src 中完全说明了图像 URL。
如果我用这个替换 showThumb 函数......
function showThumb(){
var number = 2;
var file = "/static/thumbs/" + number.toString() + "_thumb.JPG";
thumbWindow = new google.maps.InfoWindow();
thumbWindow.setContent('<img id="thumb" src="" align="middle">');
thumbWindow.setPosition(map.getCenter());
thumbWindow.open(map);
document.getElementById("thumb").src=file;
}
...我得到一个空的信息窗口和一个Uncaught TypeError: Cannot set property 'src' of null
错误。
似乎 Javascript 无法识别 InfoWindow 中的 id。
有人有办法让这个工作吗?
解决方案
似乎我问这个问题有点太早了。我有一个启示并找到了解决方案。
答案是根本不使用元素 id。
function showThumb(){
var number = 2;
var file = "/static/thumbs/" + number.toString() + "_thumb.JPG";
var imgCode = '<img id="thumb" src=' + file + ' align="middle">'
thumbWindow = new google.maps.InfoWindow();
thumbWindow.setContent(imgCode);
thumbWindow.setPosition(map.getCenter());
thumbWindow.open(map);
}
推荐阅读
- javascript - 在 Laravel 或 javascript 中自动上传文件
- angular - Angular 11如何验证confirmPassword与使用反应式表单的密码相同
- android - 找不到符号类 ActivityMainBinding
- python-3.7 - 你能帮我纠正这个错误吗:configparser?
- google-cloud-platform - Cloud SQL HA - 故障回复到哪个区域?
- python - 启动浏览器时 subprocess.call 挂起
- arrays - Mongoose - 更新嵌套数组中的多个字段
- sql-server - 使用 SQL Server Management Studio 运行作业以进行 API 调用而不是 SQL 过程
- c - 为什么一些 linux 系统调用包含一个 C 包装原型,即使 glibc 没有实现它们?
- aframe - 文本的 A-Frame 设置属性