如果你想在 DocType 表单中显示地图,可以添加一个类型为“地理位置”的字段。默认情况下,它看起来像这样:
自定义此字段的方法有很多种。我们可以更改全局设置,例如默认位置和缩放级别。我们还可以自定义特定地图上各个对象的渲染方式。
更改地图默认设置
注意:这些更改需要自定义应用,并将应用于系统中的所有地图。
默认情况下,它会显示一张以孟买为中心的城市地图。目前尚无法通过图形界面进行配置。但是,使用自定义应用,我们可以更改地图类型、起始位置、缩放级别等。
首先,创建一个文件 $MY_APP/$MY_APP/public/js/map_defaults.js。在你的 $MY_APP/$MY_APP/hooks.py 中,将 JS 文件添加到 app_include_js 钩子中:
app_include_js = [
"/assets/$MY_APP/js/map_defaults.js"
# ...
]
现在,frappe 将为所有后台视图(即已登录的系统用户)加载此文件。
在 map_defaults.js 中,我们添加以下代码行:
// Make sure we have a dictionary to add our custom settings
const map_settings = frappe.provide("frappe.utils.map_defaults");
// Center and zoomlevel can be copied from the URL of
// the map view at openstreetmap.org.
// New default location (middle of germany).
map_settings.center = [51.57, 9.866];
// new zoomlevel: see the whole country, not just a single city
map_settings.zoom = 6;
// Use a different map: satellite instead of streets
// Examples can be found at https://leaflet-extras.github.io/leaflet-providers/preview/
map_settings.tiles = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}";
map_settings.attribution = "Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community";
重启你的 bench 并重新加载浏览器窗口。现在你应该能看到自定义后的地图了:
更改特定地图的渲染方式
为了更改特定地图的外观和风格,你可以覆盖地理位置字段的控制器方法。这可以通过客户端脚本或自定义应用中的钩子来完成。
默认情况下,地图上绘制的所有内容都是蓝色的。让我们覆盖 on_each_feature 方法,使所有多边形变为红色:
frappe.ui.form.on("My Doctype", {
setup(frm) {
frm.fields_dict.MY_MAP_FIELD.on_each_feature = function(feature, layer) {
if (feature.geometry.type == "Polygon") {
layer.setStyle({color: "red"});
}
};
}
});
结果如下所示:
其他可以覆盖的方法包括 point_to_layer 和 set_style。有关这些方法的更多信息,请参阅 Leaflet 文档。