微信小程序地图展示当前位置

map.js:

const api_map = require('../../api/api_map.js');

Page({
  data: {
    point_id: '',
    point_name: '',
    point_level: '',
    point_address: '',
    isMarkerTapped: false, // 新增标志位
    latitude: 31.24230618571933,
    longitude: 121.43166880124909,
    title: '当前位置',
    polygons: [], // 用于存储多边形数据
    markers: [], // 用于存储标记数据
    clickedPoints: [], // 存储用户点击的点
  },





  // 清除多边形(可选)
  clearPolygon() {
    this.setData({
      clickedPoints: [],
      polygons: [],
      markers: [], // 清除标记点
    });
  },

  onLoad() {
    this.getCurrentLocation();
    this.getAllPosInfo();
  },

  onReady() {},

  // 获取所有位置点数据
  async getAllPosInfo() {
    const res = await api_map.getAllPosInfo();
    if (res.code === 200) {
      const resdata = res.data;
      resdata.forEach((value, index, array) => {
        let geographicInformation = JSON.parse(value.geographicInformation);
        if (geographicInformation.type === 'Polygon') {
          const coordinates = geographicInformation.coordinates;

          // 将多维坐标数组展开并提取经纬度
          const polygon = coordinates.map(ring => {
            return ring.map(coordPair => {
              // 提取经度和纬度
              return {
                latitude: coordPair[1], // 纬度
                longitude: coordPair[0], // 经度
              };
            });
          });

          // 将每个polygon添加到polygons数组中
          polygon.forEach(polygonRing => {
            this.setData({
              polygons: [...this.data.polygons, {
                points: polygonRing,
                strokeWidth: 2,
                strokeColor: "#FF0000",
                fillColor: "#FF000055", // 带透明度的填充色
                zIndex: 1,
              }]
            });
          });
        } else if (geographicInformation.type === 'Point') {

          const point = geographicInformation.coordinates;
          const latitude = point[1]; // 纬度
          const longitude = point[0]; // 经度
          const label_content = value.name;
          const label_address = value.address;
          const label_level = value.level;

          // 在地图上设置标记点
          this.setData({

            markers: [...this.data.markers, {
              id: this.data.markers.length + 1,
              latitude,
              longitude,
              title: label_content,
              address: label_address,
              level: label_level,
              // iconPath: '/resources/location.png', // 如果有资源图标路径,使用图标
              width: 30,
              height: 30,
              label: {
                content: label_content,
                color: '#000000',
                fontSize: 12,
                borderRadius: 10,
                bgColor: '#ffffff',
                padding: 2,
                borderWidth: 1, // 边框宽度
                borderColor: '#FF0000', // 边框颜色
              },



            }]
          });
        }
      });
    } else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      });
    }
  },



  // 处理标记点点击事件
  handleMarkerTap(e) {
    console.log(e)
    const markerId = e.markerId; // 获取点击的标记点 ID
    const clickedMarker = this.data.markers.find(marker => marker.id === markerId);
    console.log('点击的标记点:', clickedMarker);

    this.setData({
      point_id: clickedMarker.id,
      point_name: clickedMarker.title,
      point_level: clickedMarker.level,
      point_address: clickedMarker.address,
      isMarkerTapped: true // 标记点击了标记点

    });

  
  },




  handleMapTap() {
    // 如果点击的不是标记点(isMarkerTapped 为 false),才清空数据
    if (!this.data.isMarkerTapped) {
      this.setData({
        point_id: '',
        point_name: '',
        point_level: '',
        point_address: ''
      });
    }

    // 无论如何,都将标志位恢复为 false,等待下次点击
    this.setData({
      isMarkerTapped: false
    });
  },



  
    // 点击跳转到详情页
    goToDetailPage(event) {
      const id = event.currentTarget.dataset.id; // 获取传递的 item 对象
      const name = event.currentTarget.dataset.name;
      // 使用 wx.navigateTo 跳转到详情页面,并将 item 作为查询参数传递
      wx.navigateTo({
          url: `/pages/detail/detail?id=${id}&title=${name}`
      });
  },

  // 获取当前地理位置
  getCurrentLocation() {
    const that = this;
    wx.getLocation({
      type: 'gcj02', // 使用国测局坐标系,配合 <map> 组件用
      success(res) {
        const {
          latitude,
          longitude
        } = res;
        that.setData({
          latitude,
          longitude
        }, () => {
          that.initMap(); // 位置设置好后初始化地图
          that.setMarkers(); // 设置标记点
        });
      },
      fail(err) {
        wx.showToast({
          title: '无法获取位置',
          icon: 'none'
        });
        console.error('getLocation error:', err);
      }
    });
  },

  // 初始化地图
  initMap() {
    this.mapContext = wx.createMapContext('myMap', this);
    this.mapContext.moveToLocation(); // 把地图中心移到当前位置
  },

  // 设置当前位置标记
  setMarkers() {
    const {
      latitude,
      longitude,
      title
    } = this.data;
    this.setData({
      markers: [{
        id: 0,
        latitude,
        longitude,
        title,
        // iconPath: '/resources/location.png', // 你需要有这个图片资源,或用默认图标
        width: 30,
        height: 30,
        label: {
          content: title,
          color: '#ffffff',
          fontSize: 14,
          borderRadius: 5,
          bgColor: '#000000',
          padding: 5
        }
      }]
    });
  }
});

解释:

猜你喜欢

转载自blog.csdn.net/weixin_36152801/article/details/147087472
今日推荐