2017-09-05 125 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

相關問題