场景
Leaflet快速入门与加载OSM显示地图:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/122290880
在上面的基础上,怎样使用Leaflet.contextmenu插件实现地图上显示右键菜单效果如下
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
1、插件地址
https://github.com/aratcliffe/Leaflet.contextmenu
2、下载源码,引入所需要的leaflet.contextmenu.js文件和放大和缩小的图标文件zoom-in.png和zoom-out.png
3、修改代码中显示放大缩小图片路径地址
4、完整示例代码
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>leaflet实现鼠标右键菜单</title> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" /> <style> html, body, #map { padding: 0; margin: 0; 100%; height: 100%; overflow: hidden; } .leaflet-contextmenu { display: none; box-shadow: 0 1px 7px rgba(0, 0, 0, 0.4); -webkit-border-radius: 4px; border-radius: 4px; padding: 4px 0; background-color: #fff; cursor: default; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .leaflet-contextmenu a.leaflet-contextmenu-item { display: block; color: #222; font-size: 12px; line-height: 20px; text-decoration: none; padding: 0 12px; border-top: 1px solid transparent; border-bottom: 1px solid transparent; cursor: default; outline: none; } .leaflet-contextmenu a.leaflet-contextmenu-item-disabled { opacity: 0.5; } .leaflet-contextmenu a.leaflet-contextmenu-item.over { background-color: #f4f4f4; border-top: 1px solid #f0f0f0; border-bottom: 1px solid #f0f0f0; } .leaflet-contextmenu a.leaflet-contextmenu-item-disabled.over { background-color: inherit; border-top: 1px solid transparent; border-bottom: 1px solid transparent; } .leaflet-contextmenu-icon { margin: 2px 8px 0 0; 16px; height: 16px; float: left; border: 0; } .leaflet-contextmenu-separator { border-bottom: 1px solid #ccc; margin: 5px 0; } </style> </head> <body> <div id="map"></div> <script type="text/javascript" src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <script type="text/javascript" src="./js/leaflet.contextmenu.js"></script> <script type="text/javascript"> var map = L.map('map', { contextmenu: true, contextmenuWidth: 140, contextmenuItems: [{ text: '显示坐标', callback: showCoordinates }, { text: '作为地图中心', callback: centerMap }, '-', { text: '地图放大', icon: './icon/zoom-in.png', callback: zoomIn }, { text: '地图缩小', icon: './icon/zoom-out.png', callback: zoomOut }] }).setView([36.09, 120.35], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '' }).addTo(map); function showCoordinates(e) { alert(e.latlng); } function centerMap(e) { map.panTo(e.latlng); } function zoomIn(e) { map.zoomIn(); } function zoomOut(e) { map.zoomOut(); } </script> </body> </html>