Leaflet:如何在鼠标光标旁边显示lat / lng?

时间:2017-09-05 10:59:18

标签: leaflet

我想在Leaflet中鼠标(手)光标旁边的地图上显示当前的lat / lng。此选项也应该可以打开/关闭。

一个选项是定义一个css框,它将显示在光标旁边的地图上(只有当切换开启时,该框才可见)。该框需要显示当前的lat / lng以及随光标一起移动。

不确定如何在实践中做到这一点,我们将非常感谢您对此的任何帮助。

1 个答案:

答案 0 :(得分:2)

您可以编写一个处理程序,在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'
        })
    ]
});
body {
    margin: 0;
}

html, body, #leaflet {
    height: 100%;
}
<!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>

在上面的例子中,处理程序默认通过L.Map的cursor选项启用,该选项由处理程序创建:

var map = new L.Map(..., {
    cursor: true
});

如果您省略该选项,默认情况下它已被禁用,您可以通过map.cursor的方法启用/禁用它:

map.cursor.enable();
map.cursor.disable();

你可以将它包装在一个简单的控制按钮或其他东西中,然后你就完成了。

相关问题