我想在 . 此选项也应可切换为开/关。
一种选择是定义一个 css 框,该框将显示在光标旁边的地图顶部(该框仅在打开切换时可见)。该框需要显示当前的纬度/经度以及随光标移动。
不知道如何在实践中做到这一点,对此的任何帮助将不胜感激。
您可以编写一个处理程序,在 mouseover/mouseout 上打开/关闭弹出窗口并在 mousemove 上更新它:
L.CursorHandler = L.Handler.extend({
addHooks: function () {
this._popup = new L.Popup();
this._map.on('mouseover', this._open, this);
this._map.on('mousemove', this._update, this);
this._map.on('mouseout', this._close, this);
},
removeHooks: function () {
this._map.off('mouseover', this._open, this);
this._map.off('mousemove', this._update, this);
this._map.off('mouseout', this._close, this);
},
_open: function (e) {
this._update(e);
this._popup.openOn(this._map);
},
_close: function () {
this._map.closePopup(this._popup);
},
_update: function (e) {
this._popup.setLatLng(e.latlng)
.setContent(e.latlng.toString());
}
});
L.Map.addInitHook('addHandler', 'cursor', L.CursorHandler);
var map = new L.Map('leaflet', {
center: [0, 0],
zoom: 0,
cursor: true,
layers: [
new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
'attribution': 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
})
]
});Run Code Online (Sandbox Code Playgroud)
body {
margin: 0;
}
html, body, #leaflet {
height: 100%;
}Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<title>Leaflet 1.0.3</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
</head>
<body>
<div id="leaflet"></div>
<script type="application/javascript" src="//unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
</script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
在上面的例子中,处理程序默认通过cursor由处理程序创建的 L.Map 选项启用:
var map = new L.Map(..., {
cursor: true
});
Run Code Online (Sandbox Code Playgroud)
如果您省略该选项,默认情况下它是禁用的,您可以通过以下方法启用/禁用它map.cursor:
map.cursor.enable();
map.cursor.disable();
Run Code Online (Sandbox Code Playgroud)
您可以将其包装在一个简单的控制按钮或其他东西中,然后就完成了。