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

Python实时位置追踪:folium MarkerCluster属性错误解决求助

解决folium中MarkerCluster的AttributeError问题

你遇到的AttributeError: module 'folium' has no attribute 'MarkerCluster'错误,原因很明确:MarkerCluster不属于folium主模块,它是folium.plugins下的插件组件。

你的代码里已经写了from folium.plugins import MarkerCluster,但创建实例时还是错误地用了folium.MarkerCluster(),这就导致了属性找不到的问题。

修正步骤:

  • 保留from folium.plugins import MarkerCluster的导入语句
  • 创建MarkerCluster实例时,直接调用MarkerCluster(),不要加folium.前缀

修正后的完整代码:

import json
import paho.mqtt.client as mqtt
import folium
import time
from folium.plugins import MarkerCluster

# Variable to hold the current latitude and longitude
latitude = 50.780036278929614
longitude = 6.10363592985153

# Callback function when a message is received
def on_message(client, userdata, message):
    global latitude, longitude
    # Convert the message payload from bytes to string
    data = message.payload.decode()
    # parse the json string
    data = json.loads(data)
    # Extract the latitude and longitude
    if 'GPS' in data:
        gps_data = data["GPS"]
        latitude = gps_data["Latitude"]
        longitude = gps_data["Longitude"]

# Create MQTT client
client = mqtt.Client()

# Attach callback function to the message event
client.on_message = on_message

# Connect to the MQTT broker
client.connect("broker.mqttdashboard.com", 1883)

# Subscribe to the desired topic
client.subscribe("gpsdata")

# Start the MQTT loop
client.loop_start()

# Initialize the map
m = folium.Map(location=[latitude, longitude], zoom_start=15)

# 直接使用导入的MarkerCluster类,不要加folium.前缀
mc = MarkerCluster()
m.add_child(mc)

marker = None
while True:
    # Check if the latitude and longitude have been updated
    if latitude and longitude:
        # Remove the previous marker
        if marker:
            mc.remove_child(marker)
        # Update the marker on the map to the current location
        marker = folium.Marker(location=[latitude, longitude])
        mc.add_child(marker)

        # Save the map
        m.save("current_location.html")
    # Wait for one second
    time.sleep(1)

额外提示:

当前代码每次循环都会重新保存HTML文件,但浏览器不会自动刷新这个文件。如果想要实时看到位置更新,你可以考虑:

  • 用浏览器的自动刷新插件定时刷新current_location.html
  • 或者改用Flask/Django等web框架,通过websocket实时推送位置更新到前端

内容的提问来源于stack exchange,提问作者AJ E.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:30:52