我***需要***扩展 Leaflet 的标记 class 来添加属性吗?
Do I ***need*** to extend Leaflet's marker class to add properties?
这是我很少做的事情 - 向 Leaflet 标记添加属性。
我在读 this page 上面说我们应该
customMarker = L.Marker.extend({
options: {
name: '',
type: ''
}
});
var marker = new customMarker([28.63278, 77.21972],{
clickable: true,
name: 'Connaught Place',
type: 'Neighbourhood'
}).addTo(map);
我从一些旧代码中看到我只是
let marker = L.marker(markerLatLng, {
name: 'Connaught Place',
type: 'Neighbourhood'
因为这个有效,Leaflet 似乎足够智能,可以将任何非 Leaflet 属性视为扩展 L.Marker class.
是否有“正确”的方法(具有正确的技术原因)?
不,您真的不需要为了能够添加自己的数据而扩展 Leaflet 层。
您 link 的博客 post 可以追溯到 2013 年,因此 可能 当时是另一回事。
使用今天的 Leaflet 版本(撰写本文时为 1.7.1),如果您这样做:
const myMarker = L.marker(latLng, {
myData: someData
});
...然后您可以使用以下方法检索一些数据:
myMarker.options.myData; // someData
话虽这么说,当您想扩展博客中显示的此类选项时可能会有一些用例 post:如果您想要一些默认值,如 https://leafletjs.com/reference-1.7.1.html#class-options 中所述
[...] makes managing configuration of objects and default values convenient
否则,您还可以通过其他方式将数据附加到 Leaflet 图层,请参阅 Leaflet: Including metadata with CircleMarkers
这是我很少做的事情 - 向 Leaflet 标记添加属性。
我在读 this page 上面说我们应该
customMarker = L.Marker.extend({
options: {
name: '',
type: ''
}
});
var marker = new customMarker([28.63278, 77.21972],{
clickable: true,
name: 'Connaught Place',
type: 'Neighbourhood'
}).addTo(map);
我从一些旧代码中看到我只是
let marker = L.marker(markerLatLng, {
name: 'Connaught Place',
type: 'Neighbourhood'
因为这个有效,Leaflet 似乎足够智能,可以将任何非 Leaflet 属性视为扩展 L.Marker class.
是否有“正确”的方法(具有正确的技术原因)?
不,您真的不需要为了能够添加自己的数据而扩展 Leaflet 层。
您 link 的博客 post 可以追溯到 2013 年,因此 可能 当时是另一回事。
使用今天的 Leaflet 版本(撰写本文时为 1.7.1),如果您这样做:
const myMarker = L.marker(latLng, {
myData: someData
});
...然后您可以使用以下方法检索一些数据:
myMarker.options.myData; // someData
话虽这么说,当您想扩展博客中显示的此类选项时可能会有一些用例 post:如果您想要一些默认值,如 https://leafletjs.com/reference-1.7.1.html#class-options 中所述
[...] makes managing configuration of objects and default values convenient
否则,您还可以通过其他方式将数据附加到 Leaflet 图层,请参阅 Leaflet: Including metadata with CircleMarkers