2017-09-05 131 views
0

我想在Leaflet中鼠标(手形)光标旁边的地图上显示当前经纬度/ lng。这个选项也应该可以切换为开/关。小册子:如何在鼠标光标旁边显示lat/lng?

一个选择是定义一个css框,它将显示在地图上的光标旁边(只有在开关处于打开状态时,该框才会显示)。该框需要显示当前的纬度/经度,以及与光标一起移动。

不知道如何在实践中做到这一点,任何帮助将不胜感激。

回答

1

你可以写一个打开处理器/关闭鼠标悬停/鼠标移开一个弹出式和更新它的鼠标移动:

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/[email protected]/dist/leaflet.css" /> 
 
    </head> 
 
    <body> 
 
    <div id="leaflet"></div> 
 
    <script type="application/javascript" src="//unpkg.com/[email protected]/dist/leaflet.js"></script> 
 
</script> 
 
    </body> 
 
</html>

在上面的例子中,处理器默认情况下,通过启用cursor由处理器创建的L.Map选项:

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

如果您遗漏了t帽子选择它的默认禁用,您可以启用/通过map.cursor方法关闭之:

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

你可以用在一个简单的控制按钮或东西,你就大功告成了。

+0

整洁!感谢您抽出时间来创建完整的演示:) – BigONotation

相关问题