簡體   English   中英

使用 javascript 變量設置 img src 以在 Google Maps InfoWindow 中使用

[英]Setting img src using a javascript variable for use in a 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.

如果我用這個替換 showThumb function ......

    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 和一個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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM