网页 H5 搭配 leaflet 图 展示地图 可以用图片覆盖地图

Documentation - Leaflet - 一个交互式地图 JavaScript 库

因为公司想做一个 图片可以覆盖在地图上的方式,最开始的时候使用了 uniapp 中的map 组件,虽然也能覆盖, 但是功能不是很完善 ,很齐全, 然后就开始找各种的方法找到了这个 

也是做好了之后,在嵌入在app 中

首先 我们要在安装包  npm install leaflet   

然后 要在index.html 引入外部资源  建议可以转化成自己的资源 因为外部的链接 会导致图片渲染很慢,感觉不是很好 ,还会限制图片的大小 ,图片建议不要很大 这样很容易出不来

<script src="https://cdn.jsdelivr.net/npm/leaflet-rotatedmarker"></script> 

<template>
 <div id="map" class="map"></div>
</template>
<script>
import "leaflet/dist/leaflet.css";
import { getAction } from "../utils/httpRequest.js";
import L from "leaflet";
import { marker } from "leaflet";

export default{

data(){
  notclick: true,
      map: null, //初始化 map 对象
      trackPoints: [
        //自行获取数据
      ],
      result: "",
      mMap: "",
      gdtbLayerId: 0,
      center: {
        latitude: "", //纬度
        longitude: "", //经度
      },
      scale: 16,
      bkUrl: "",
      bkUrl1: "",
      params: {
        id: "", //当前景点id 【首页-景点列表】接口返回的
      },
      title: "",
      markes: [],
      fanwei: {
        northeast: {
          longitude: 118.800805,
          latitude: 32.04637,
        },
        southwest: {
          longitude: 118.794078,
          latitude: 32.042279,
        },
      },
},
mounted() {
    this.getScenicDetail();
 
  },
methods:{
async getScenicDetail() {
      await getAction(`接口`)
        .then((res) => {
          // console.log(res.data.result)
          this.name = res.data.result.name;
          if (res.data.result.drawImg.split(",")[1]) {
            if (
              this.condition.find((item) =>
                res.data.result.drawImg.split(",")[0].includes(item)
              )
            ) {
              this.bkUrl = res.data.result.drawImg.split(",")[1];
              this.bkUrl1 = res.data.result.drawImg.split(",")[0];
            } else {
              this.bkUrl = res.data.result.drawImg.split(",")[0];
              this.bkUrl1 = res.data.result.drawImg.split(",")[1];
            }
          } else {
            this.bkUrl = res.data.result.drawImg;
          }
          this.result = JSON.parse(res.data.result.scope);
          this.fanwei.northeast.longitude = this.result[1][1];
          this.fanwei.northeast.latitude = this.result[1][0];
          this.fanwei.southwest.longitude = this.result[0][1];
          this.fanwei.southwest.latitude = this.result[0][0];
          this.scale = res.data.result.scale;
          this.minScale = res.data.result.zoomScale.split(",")[0];
          this.maxScale = res.data.result.zoomScale.split(",")[1];
          this.center.latitude = res.data.result.glat;
          this.center.longitude = res.data.result.glng;
          this.mark = res.data.result.markers;
          this.description = res.data.result.description;
          this.cityName = res.data.result.cityName;
          this.provinceName = res.data.result.provinceName;
          this.coverImg = res.data.result.coverImg;
          this.level = res.data.result.level;
          this.lengthTotal = this.mark.length;
          this.descriptionAudio = res.data.result.descriptionAudio;
          this.myinitMap();
          setTimeout(() => {
            this.loadingkey = false;
          }, 2500);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getMarkList() {
      this.doMarks();
    },

doMarks(){
this.mark.forEach((marker) => {
          const latitude = JSON.parse(marker.location)[0];
          const longitude = JSON.parse(marker.location)[1];
          const title = marker.name;
          var customIcon = L.divIcon({
            className: "custom-icon",
            html: `<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center;">
			              <div style="font-size:0">
			                  <img src="https://static.yzb10086.com/trip/banner/img/file_label_20240611144911712_zbvo.png" style="width: 25px; height: 22px;">
			              </div>
			              <span style="color:#000; font-size:10px; background: linear-gradient(to right,rgba(255,255,255,0.2),rgba(255,255,255,1),rgba(255,255,255,0.2)); padding:2px; border-radius:6px; width: 50px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${title}</span>
			          </div>`,
            iconAnchor: [0, 50],
          });
          var lmarker = L.marker([latitude, longitude], {
            id: marker.id,
            icon: customIcon,
          });

          //标记点的点击事件
          lmarker.on("click", (e) => {
          
            var clickedMarkerId = e.target.options.id;
            const clickedMarker = this.mark.find(
              (marker) => marker.id === clickedMarkerId
            );
            this.MarkPointObject = clickedMarker;
            if (clickedMarker) {
              const [latitude, longitude] = JSON.parse(clickedMarker.location);
              // 将地图视图定位到点击的标记点坐标并放大显示
              this.map.setView([latitude, longitude], this.maxScale);
          
            } else {
              console.log("没有找到与 clickedMarkerId 相匹配的对象");
            }
          });
          // 将标记点存储在数组中
          this.allMarkers.push(lmarker);
        });
      }

     
      // 显示初始的标记点
      this.showMarkers(this.currentMarkersToShow);
      // 监听地图缩放事件
      this.map.on("zoomend", () => {
        let currentZoom = this.map.getZoom();
        // 在适当的缩放级别加载更多的标记点
        if (currentZoom > 16) {
          // 你可以根据实际情况调整这个缩放等级
          this.currentMarkersToShow = this.allMarkers.length; // 显示所有标记点
        } else {
          this.currentMarkersToShow = maxMarkersToShow; // 重置为显示40个标记点
        }
        this.showMarkers(this.currentMarkersToShow);
      });
    }
},
 showMarkers(count) {
      // 清除地图上的所有标记点
      this.clearMarkers();
      // 添加指定数量的标记点到地图上
      for (let i = 0; i < count && i < this.allMarkers.length; i++) {
        this.allMarkers[i].addTo(this.map);
      }
    },
    clearMarkers() {
      // 移除地图上的所有标记点
      this.allMarkers.forEach((marker) => {
        this.map.removeLayer(marker);
      });
    },
    myinitMap() {
      // 定义图像加载的边界值(即在地图上的大小、位置)
      var imageBounds = [
        [this.fanwei.southwest.latitude, this.fanwei.southwest.longitude],
        [this.fanwei.northeast.latitude, this.fanwei.northeast.longitude],
      ]; // 将图片作为自定义图层加载到地图上(类似于Marker)
      if (this.bkUrl) {
        var overlay = L.imageOverlay(this.bkUrl, imageBounds, {
          opacity: 1,
          zIndex: 20,
        });
        this.overlay1 = L.imageOverlay(this.bkUrl1, imageBounds, {
          opacity: 2,
          zIndex: 21,
        });
        this.map = L.map("map", {
          center: L.latLng(this.center.latitude, this.center.longitude), // 地图中心
          zoom: this.scale, // 缩放比例
          minZoom: this.minScale, // 设置最小缩放级别
          maxZoom: this.maxScale, // 设置最大缩放级别
          doubleClickZoom: true, // 禁用双击放大
          attributionControl: false, // 移除右下角 Leaflet 标识
        });
        overlay.addTo(this.map); // 添加图片覆盖物到地图
      } else {
        this.map = L.map("map", {
          center: L.latLng(this.center.latitude, this.center.longitude), // 地图中心
          zoom: this.scale, // 缩放比例
          minZoom: this.minScale, // 设置最小缩放级别
          maxZoom: this.maxScale, // 设置最大缩放级别
          doubleClickZoom: true, // 禁用双击放大
          attributionControl: false, // 移除右下角 Leaflet 标识
        });
        L.tileLayer(
          "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",
          {
            maxZoom: 18,
            attribution: "© AutoNavi",
          }
        ).addTo(this.map);
      }
      var maxBounds = L.latLngBounds(
        L.latLng(
          this.fanwei.southwest.latitude,
          this.fanwei.southwest.longitude
        ),
        L.latLng(
          this.fanwei.northeast.latitude,
          this.fanwei.northeast.longitude
        )
      );
      this.map.setMaxBounds(maxBounds); // 将放大缩小控件从左上方移动到右下方
      //放大缩小的图标
      L.control
        .zoom({
          position: "bottomright",
        })
        .addTo(this.map);
      this.getMarkList(); // 加载标记 // 监听地图移动事件,确保地图在指定边界范围内移动
      this.map.on("mousemove", (e) => {
        var latlng = e.latlng;
      });
    },

 
}


}


</script>

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值