在Google Maps信息窗口中使用javascript变量设置img src
我试图打开一个GoogleMaps信息窗口来显示图像,但我想用javascript变量定义图像源 下面是我使用Flask编写的Python代码在Google Maps信息窗口中使用javascript变量设置img src,javascript,image,google-maps-api-3,infowindow,Javascript,Image,Google Maps Api 3,Infowindow,我试图打开一个GoogleMaps信息窗口来显示图像,但我想用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 Map
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;
}
。。。我得到一个空的InfoWindow和一个未捕获的TypeError:无法设置null error的属性'src'
Javascript似乎无法识别信息窗口中的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);
}
id=thumb的元素在DOM中不存在。在将其添加到DOM之前,document.getElementById无法找到该元素。在.open被处理并在后台异步处理之后,它才会出现在DOM中