前言
足迹地图我很早就知道咯,一直没有办法实现它,大发的地图插件Marker Pro很喜欢,但只是看看而已。直到发现了它——Leaflet,一个开源JavaScript库,适用于适合移动设备的交互式地图。
只不过我的博客在国内,想着多一事不如少一事,图源换成国内的应该好点儿(我换成高德了),原理它差不多。就像博友说的,使用国外图源,一不小心,把一小块地画给国外,就是勾结外部势力了。话不多说,上教程。
步骤
我的想法是新建页面模版,独立页面显示。文章源自三无青年-https://www.duanxiansen.com/2332.html
1、准备工作文章源自三无青年-https://www.duanxiansen.com/2332.html
新建footprint.js文件,footprint.js文件应包含你的足迹点数据,上传这个文件到你主题目录的js文件里,比如:文章源自三无青年-https://www.duanxiansen.com/2332.html
/wp-content/themes/your-theme/js/footprint.js
文章源自三无青年-https://www.duanxiansen.com/2332.html
footprint.js文件的内容文章源自三无青年-https://www.duanxiansen.com/2332.html
const footprint = [ ["<b>银川</b><i>Yinchuan</i><a href='https://www.duanxiansen.com/84.html/'>银川镇北堡西部影视城三日游</a>", 38.46667, 106.26667], ["<b>榆中</b><i>Yuzhong</i><a href='https://www.duanxiansen.com/1303.html/'>记第一次滑雪</a>", 36.0620781, 103.8318566], ["<b>白银</b><i>Baiyin</i><a href='https://www.duanxiansen.com/1115.html/'>游黄河石林景区(公司第一次团建)</a>", 36.5340173, 104.1467575], // 添加更多点 ];
文章源自三无青年-https://www.duanxiansen.com/2332.html
2、创建自定义页面模版文件文章源自三无青年-https://www.duanxiansen.com/2332.html
新建page-map.php文件,放在你的主题页面模版文件夹里。文章源自三无青年-https://www.duanxiansen.com/2332.html
<?php /* Template Name: 足迹地图 */ get_header(); ?> <style> #map { width: 100%; max-width: 1200px; height: 500px; margin: 0 auto; } </style> <div id="map" class="other-map"></div> <script src="https://webapi.amap.com/maps?v=1.4.15&key=您的高德地图API密钥"></script> <script type="text/javascript" src="<?php echo get_stylesheet_directory_uri(); ?>/js/footprint.js"></script> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { var map = new AMap.Map('map', { center: [116.397128, 39.916527], zoom: 4 }); if (typeof footprint !== 'undefined' && footprint.length > 0) { for (let i = 0; i < footprint.length; i++) { const [popupText, lat, lng] = footprint[i]; var marker = new AMap.Marker({ position: new AMap.LngLat(lng, lat), map: map }); marker.on('click', function() { var infoWindow = new AMap.InfoWindow({ content: popupText, offset: new AMap.Pixel(0, -30) }); infoWindow.open(map, marker.getPosition()); }); } } else { console.error('footprint array is undefined or empty'); } }); </script> <?php get_footer(); ?>
自行申请高德地图API密钥。注意上述代码中js的路径文章源自三无青年-https://www.duanxiansen.com/2332.html
/js/footprint.js"
结尾
过程很复杂,我简化了步骤,直接操作会很简单,不过相比较使用Leaflet,任有许多不完美之处,比如点击标记点显示文章图片,Leaflet会自动生成缩略图,而这个显示原图,所以我去掉了图片显示。鼠标滑过标记点,Leaflet会自动显示标记点文章,而这个需要点击标记点,而且点开之后需要手动关闭才能浏览下个标记点。Leaflet则不需要,随便点击空白处就关闭了。相比较,Leaflet更完美,体验感更足。文章源自三无青年-https://www.duanxiansen.com/2332.html
嘿嘿,这不,时间就这样过去了