前端leaflet.js 加载SVG地图或者图片,实现缩放拖拽

首先去bootcdn 下载 leaflet.js 以及leaflet.css。此外leaflet.css有一些背景图的图标也可以在这儿找到。

官方文档

我这篇文章仅仅针对于导入svg地图或者纯图片地图时使用,比如你放入房子的平面图

首先导入内容

<link rel="stylesheet" href="./styles/leaflet.css">    
<script src="./scripts/leaflet.js"></script>
<body>
<div id="map"></div>
</body>

 js代码:

function loadMap(){ 
 const svgUrl = "./svg/BZ.svg";

//   const svgUrl = "./asset/images/TF.png";
    
    const map = L.map('map', {
        minZoom:-2,
        maxZoom: 5,
        zoom:1,
        crs: L.CRS.Simple,
        trackResize:true
    })

    var bounds = [[0,0], [4081,7257]]; //起始点 0,0 以图片左下角起以及终点换算  表示像素坐标中的矩形区域。
    var image = L.imageOverlay(svgUrl, bounds).addTo(map);


    var sol = L.latLng([ 0,0 ]); // x,y 相反
   const marker= L.marker(sol).addTo(map); // 图标,图标样式来源于leaflet.css 需要下载好图片
    map.setView( [0, 0], 1); // 设置中心点,这个中心点将图片坐标位于外面父元素中心点,建议地图中心,我这个是起点;第二个参数应该是缩放倍数,
    // map.setView( [70, 120], 1);

// 给图标添加事件
 marker.on("mouseover", e => {
       //添加文字的方法
       var html=`
            <div style="padding:10px;background:yellow">我是弹窗</div>
       `

       marker.bindPopup(html).openPopup();
        // alert("咩哈哈")
    })

    // 右下角文字编辑
    const rightBottomTitle= document.querySelector(".leaflet-control-attribution")
    rightBottomTitle.innerHTML=""
}

  

 

  我这里面bounds = [[0,0], [4081,7257]]

 是设置他的起始点以及终止点,因为有的图片可能边缘部分空白用不上,这时候换算就会出现差错,比如图片边缘有10单位的空白,那么起始点就是[10,10],终止点就是[4071,7247]。这个Svg宽高是:7257,4081这里的坐标参数实际上是(y,x)。也就是你获取坐标进行展示图标的时候需要进行换算一下。比如:

function transform(position){
  return {
      x:position.y,
      y:position.x
    }
}
const point =transform({x:0,y:1});

  

 

posted @ 2022-07-11 16:22  越甲鸣吾君  阅读(1187)  评论(0编辑  收藏  举报