【问题标题】:Change Leaflet layer control icons on mobile devices?更改移动设备上的传单图层控制图标?
【发布时间】:2020-07-31 09:41:41
【问题描述】:

我非常感兴趣地关注了这篇文章 Change leaflet layer control icons 并实施了建议的代码来更改 Leaflet 图层切换按钮的图标。这在桌面浏览器上运行良好,请参阅图像 collapsed layers switchexpanded layers switch

但是,我已经在不同移动设备上的相当多的浏览器上进行了测试,它始终是出现在图层开关上的默认 Leaflet 图标 (collapsed layers switch, mobile)。我们如何在移动设备上也更改图标?

【问题讨论】:

  • 不同的移动浏览器也会出现这种情况吗?

标签: javascript leaflet


【解决方案1】:

玩了一会儿后,我想出了https://jsitor.com/WIM0PnQH2。它适用于 Android 9、Firefox 和 Chrome 浏览器。

我通常不建议深入了解 Leaflet 内部方法,但我没有看到更简洁的实现方式。您还需要实现 CSS。

var map = L.map("map").setView([19.04469, 72.9258], 12);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var controllayer1 = L.control.layers({ map: map }, {}).addTo(map);

L.Control.Layers2 = L.Control.Layers.extend({
  _initLayout: function () {
    L.Control.Layers.prototype._initLayout.call(this);

    //replacing rather than overriding in case leaflet internal methods change in the future
    let ownclasses = this._layersLink.getAttribute('class');
    this._layersLink.setAttribute('class', ownclasses.replace('leaflet-control-layers-toggle', 'leaflet-control-layers-toggle-2'))

  }
});

L.control.layers2 = function (...args) {
  return new L.Control.Layers2(...args);
};

var controllayer2 = L.control.layers2({ map: map }, {}).addTo(map);
#map {
  height: 500px;
  width: 80%;
}

.leaflet-bar a,
.leaflet-control-layers-toggle-2 {
    background-position: 50% 50%;
    background-repeat: no-repeat;
    display: block;
    }

.leaflet-control-layers-toggle-2 {
  background-image: url(https://mejrs.github.io/mejrs.github.io/images/favicon_skavid_map.png);
  width: 36px;
  height: 36px;
}
//Should really be a higher detail version
.leaflet-retina .leaflet-control-layers-toggle-2 {
  background-image: url(https://mejrs.github.io/mejrs.github.io/images/favicon_skavid_map.png);
  background-size: 26px 26px;
}

.leaflet-touch .leaflet-control-layers-toggle-2 {
  width: 44px;
  height: 44px;
}

.leaflet-control-layers-expanded .leaflet-control-layers-toggle-2 {
  display: none;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
</head>

<body>

    <div id="map"></div>
</body>

</html>

【讨论】:

  • @kvothe 提出的解决方案效果很好。我在旧 iphone (5S) 上的 Chrome 和 Safari 上对其进行了测试。
猜你喜欢
  • 1970-01-01
  • 2015-05-17
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2014-01-09
  • 1970-01-01
相关资源
最近更新 更多