You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly Dash应用中显示Google Maps标记?

在Plotly Dash中集成带自定义标记的Google Maps的方案

方案1:嵌入gmplot生成的HTML(最快上手)

你已经能用gmplot生成带标记的Google Maps HTML,直接用Dash的html.Iframe组件把这个页面嵌入到Dash应用里就行,完全不用写JS。

步骤:

  1. 把gmplot生成的HTML文件放到Dash项目的assets目录下(没有的话新建一个),Dash会自动识别这个静态资源目录。
  2. 修改你的gmplot代码,将生成路径指向assets:
path = "assets/map11.html"
API_KEY = "VERYLONGAPICODEHERE"

gmaps_key = googlemaps.Client(key=API_KEY)
add_1 = 'London, UK'
g = gmaps_key.geocode(add_1)
lat = g[0]["geometry"]["location"]["lat"]
long = g[0]["geometry"]["location"]["lng"]

gmap1 = gmplot.GoogleMapPlotter(lat, long, 17, apikey=API_KEY)
gmap1.marker(lat, long, 'green', title="Map works")
gmap1.text(lat, long,  "Important Info Hero", color='#09541d')
gmap1.draw(path)
  1. 编写Dash应用代码,用Iframe加载生成的HTML:
from dash import Dash, html

app = Dash(__name__)

app.layout = html.Div([
    html.H1("Google Maps in Dash"),
    html.Iframe(
        src="/assets/map11.html",
        width="100%",
        height="600px"
    )
])

if __name__ == "__main__":
    app.run_server(debug=True)

启动Dash应用后,就能看到带自定义标记和文本的Google Maps页面正常显示。

方案2:直接集成Google Maps API(无iframe,更原生)

如果不想用iframe,也可以直接在Dash里通过Python配置Google Maps,无需写复杂JS逻辑。核心是用html.Div作为地图容器,通过html.Script加载API并渲染标记,标记数据从Python直接传递到前端。

示例代码:

from dash import Dash, html

app = Dash(__name__)

# 标记数据(可从Python动态生成)
markers = [
    {"lat": 51.5074, "lng": -0.1278, "title": "Map works", "text": "Important Info Hero"}
]

app.layout = html.Div([
    html.H1("原生Google Maps集成"),
    html.Div(id="map-container", style={"width": "100%", "height": "600px"}),
    html.Script(f"""
        function initMap() {{
            const center = {{lat: {markers[0]['lat']}, lng: {markers[0]['lng']}}};
            const map = new google.maps.Map(document.getElementById('map-container'), {{
                zoom: 17,
                center: center
            }});
            // 批量添加标记和信息窗口
            {''.join([f'''
            const marker{idx} = new google.maps.Marker({{
                position: {{lat: {m['lat']}, lng: {m['lng']}}},
                map: map,
                title: "{m['title']}",
                icon: "http://maps.google.com/mapfiles/ms/icons/green-dot.png"
            }});
            const infowindow{idx} = new google.maps.InfoWindow({{
                content: "<div style='color:#09541d'>{m['text']}</div>"
            }});
            marker{idx}.addListener('click', () => {{
                infowindow{idx}.open(map, marker{idx});
            }});
            ''' for idx, m in enumerate(markers)])}
        }}
    """),
    html.Script(src=f"https://maps.googleapis.com/maps/api/js?key=VERYLONGAPICODEHERE&callback=initMap")
])

if __name__ == "__main__":
    app.run_server(debug=True)

这个方案里,标记数据由Python定义,通过字符串格式化传递到JS脚本中,点击标记还能弹出交互性的信息窗口,比gmplot的静态文本体验更好。

方案3:用Plotly原生地图替代(无需Google API)

如果不想依赖Google Maps API,也可以用Plotly原生地图(基于OpenStreetMap)实现类似效果,全程用Python代码完成:

from dash import Dash, dcc, html
import plotly.graph_objects as go

app = Dash(__name__)

lat = 51.5074
long = -0.1278

fig = go.Figure(go.Scattermapbox(
    lat=[lat],
    lon=[long],
    mode='markers+text',
    marker=dict(size=15, color='green'),
    text=["Important Info Hero"],
    textposition="top center",
    textfont=dict(color='#09541d')
))

fig.update_layout(
    mapbox_style="open-street-map",
    mapbox=dict(
        center=dict(lat=lat, lon=long),
        zoom=17
    ),
    margin={"r":0,"t":0,"l":0,"b":0}
)

app.layout = html.Div([
    html.H1("Plotly原生地图"),
    dcc.Graph(figure=fig)
])

if __name__ == "__main__":
    app.run_server(debug=True)

这个方案不需要Google API密钥,所有逻辑用Python实现,能快速达成标记和文本展示的需求,唯一区别是底图为OpenStreetMap而非Google Maps。


内容的提问来源于stack exchange,提问作者Maks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 15:19:31