传单如何显示与属性文本内联的地图比例?

Leaflet how to show map scale inline with attribution text?

我想使用 L.control.scale() 显示传单地图的比例,但是我想以与 Google 地图 API 提供的方式相同的方式定位比例。我需要比例尺与地图属性一致。我在下面附上了一张图片。

Google 地图API(我多么想要)

传单(目前的样子)

我正在使用以下代码创建比例尺并将其添加到我的地图中。

L.control.scale().addTo(map);

要简单地将比例尺放在地图的同一角作为属性,您可以在创建比例尺控件时设置position option

L.control.scale({position:'bottomright', metric: false}).addTo(map);

要使比例实际与属性一致,您可以创建一个包含比例小部件和属性文本的自定义控件。 Leaflet 被设计为可扩展的,因此您可以将 source code 扩展为 L.Control.Scale 以仅添加您需要的内容:

L.Control.AttrScale = L.Control.Scale.extend({
  onAdd: function (map) {
    var className = 'leaflet-control-scale',
        wrapper = L.DomUtil.create('div', 'leaflet-control-attr-scale'),
        attribution = L.DomUtil.create('div', 'leaflet-control-attribution', wrapper),
        container = L.DomUtil.create('div', className, wrapper),
        options = this.options;
        
    wrapper.style.display = "flex";
    wrapper.style.alignItems = "center";

    attribution.innerHTML = "My attribution string";

    this._addScales(options, className + '-line', container);

    map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
    map.whenReady(this._update, this);

    return wrapper;
  },
});

map.addControl(new L.Control.AttrScale({position:'bottomright', metric: false}))

上面的示例显示了比例前的静态属性字符串。您仍然可以使用常规选项来定位控件并设置是否显示公制 and/or 英制刻度。您可能还想使用 attributionControl: false 选项创建地图,以避免显示默认属性。

如果您需要根据地图选择动态设置属性消息(就像普通属性控件一样),请查看 source codeL.Control.Attribution 以查看您需要哪些额外功能合并到自定义控件中。