问题描述
我是编程和 Python 的初学者.我有一个使用 dash-leaflet 构建的地图应用程序,其中包含 dl.GeoJSON 组件中包含的几个(~10)GeoJSON 文件.我想显示一个包含每个文件的所有属性的弹出窗口.在实施 dl.GeoJSON 之前,我曾经通过读取我的 geojson 并像这样定义弹出窗口来创建我的图层:
I am a very beginner in programmation and Python. I have a map application built with dash-leaflet with several (~10) GeoJSON files included by dl.GeoJSON component. I would like to show a popup with all the properties of each file. Before dl.GeoJSON was implemented, i used to create my layers by reading my geojson and defining popup like this :
def compute_geojson(gjson):
geojson = json.load(open(gjson["path"],encoding='utf8'))
if 'Polygon' in geojson["features"][0]["geometry"]["type"]:
data = [
dl.Polygon(
positions=get_geom(feat),
children=[
dl.Popup([html.P(k + " : " + str(v)) for k,v in feat["properties"].items()],maxHeight=300),
],
color=get_color(gjson,feat), weight=0.2, fillOpacity=gjson["opacity"], stroke=True
) for feat in geojson['features']
]
...
我想使用组件 dl.GeoJSON 为我的所有 geojson(具有不同的结构)执行此操作,因为它应该比我的方法呈现得更快.是否可以 ?我用 onEachFeature 尝试了一些 javascript,但没有成功.
I would like to do this for all my geojson (which have different structures) with the component dl.GeoJSON because it should render faster than my method. Is it possible ? I tried some javascript with onEachFeature but didn't succeed.
谢谢
推荐答案
最简单的解决方案是添加一个名为 popup
的特性和所需的弹出内容,作为 GeoJSON
组件会自动将其呈现为弹出窗口,
The simplest solution would be to add a feature named popup
with the desired popup content, as the GeoJSON
component will render it as a popup automatically,
import dash_leaflet as dl
import dash_leaflet.express as dlx
data = dlx.dicts_to_geojson([dict(lat=-37.8, lon=175.6, popup="I am a popup")])
geojson = dl.GeoJSON(data=data)
如果您需要更多自定义选项和/或不想添加属性(例如出于性能原因),您需要实现自定义 onEachFeature
函数.如果您在资产文件夹中创建一个 .js 文件,其内容如下
If you need more customization options and/or prefer not to add properties (e.g. for performance reasons), you would need to implement a custom onEachFeature
function. If you create a .js file in your assets folder with content like,
window.someNamespace = Object.assign({}, window.someNamespace, {
someSubNamespace: {
bindPopup: function(feature, layer) {
const props = feature.properties;
delete props.cluster;
layer.bindPopup(JSON.stringify(props))
}
}
});
你可以像这样绑定函数,
you can bind the function like this,
import dash_leaflet as dl
from dash_extensions.javascript import Namespace
ns = Namespace("someNamespace", "someSubNamespace")
geojson = dl.GeoJSON(data=data, options=dict(onEachFeature=ns("bindPopup")))
在上面的代码示例中,我使用了 dash-leaflet==0.1.10
和 dash-extensions==0.0.33
.
In the above code examples i am using dash-leaflet==0.1.10
and dash-extensions==0.0.33
.
这篇关于使用 Python Dash-Leaflet 将模板弹出窗口添加到 GeoJSON 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!