好客租房173-地图找房createCircle方法

1复用之前创建覆盖物的代码逻辑

在覆盖物的单击事件中 调用renderOverLays(id)方法

import React from 'react'

// 导入axios
import axios from 'axios'

// 导入封装好的 NavHeader 组件
import NavHeader from '../../components/NavHeader'

// 导入样式
// import './index.scss'
import styles from './index.module.css'

// 解决脚手架中全局变量访问的问题
const BMapGL = window.BMapGL

// 覆盖物样式
const labelStyle = {
  cursor: 'pointer',
  border: '0px solid rgb(255, 0, 0)',
  padding: '0px',
  whiteSpace: 'nowrap',
  fontSize: '12px',
  color: 'rgb(255, 255, 255)',
  textAlign: 'center'
}

export default class Map extends React.Component {
  componentDidMount() {
    this.initMap()
  }

  // 初始化地图
  initMap() {
    // 获取当前定位城市
    const { label, value } = JSON.parse(localStorage.getItem('hkzf_city'))
    // console.log(label, value)

    // 初始化地图实例
    const map = new BMapGL.Map('container')
    // 作用:能够在其他方法中通过 this 来获取到地图对象
    this.map = map
    // 创建地址解析器实例
    const myGeo = new BMapGL.Geocoder()
    // 将地址解析结果显示在地图上,并调整地图视野
    myGeo.getPoint(
      label,
      async point => {
        if (point) {
          //  初始化地图
          map.centerAndZoom(point, 11)
          // 添加常用控件
          map.addControl(new BMapGL.NavigationControl())
          map.addControl(new BMapGL.ScaleControl())

          // 调用 renderOverlays 方法
          this.renderOverlays(value)
          /* 
            渲染所有区覆盖物
          */
          /* const res = await axios.get(
            `http://localhost:8080/area/map?id=${value}`
          )
          res.data.body.forEach(item => {
            // 为每一条数据创建覆盖物
            const {
              coord: { longitude, latitude },
              label: areaName,
              count,
              value
            } = item

            // 创建坐标对象
            const areaPoint = new BMapGL.Point(longitude, latitude)
            // 创建覆盖物
            const label = new BMapGL.Label('', {
              position: areaPoint,
              offset: new BMapGL.Size(-35, -35)
            })

            // 给 label 对象添加一个唯一标识
            label.id = value

            // 设置房源覆盖物内容
            label.setContent(`
              <div class="${styles.bubble}">
                <p class="${styles.name}">${areaName}</p>
                <p>${count}套</p>
              </div>
            `)

            // 设置样式
            label.setStyle(labelStyle)

            // 添加单击事件
            label.addEventListener('click', () => {
              console.log('房源覆盖物被点击了', label.id)

              // 放大地图,以当前点击的覆盖物为中心放大地图
              map.centerAndZoom(areaPoint, 13)

              // 解决清除覆盖物时,百度地图API的JS文件自身报错的问题
              setTimeout(() => {
                // 清除当前覆盖物信息
                map.clearOverlays()
              }, 0)
            })

            // 添加覆盖物到地图中
            map.addOverlay(label)
          }) */
        }
      },
      label
    )
  }

  // 渲染覆盖物入口
  // 1 接收区域 id 参数,获取该区域下的房源数据
  // 2 获取房源类型以及下级地图缩放级别
  async renderOverlays(id) {
    const res = await axios.get(`http://localhost:8080/area/map?id=${id}`)
    // console.log('renderOverlays 获取到的数据:', res)
    const data = res.data.body

    // 调用 getTypeAndZoom 方法获取级别和类型
    const { nextZoom, type } = this.getTypeAndZoom()

    data.forEach(item => {
      // 创建覆盖物
      this.createOverlays(item, nextZoom, type)
    })
  }

  // 计算要绘制的覆盖物类型和下一个缩放级别
  // 区   -> 11 ,范围:>=10 <12
  // 镇   -> 13 ,范围:>=12 <14
  // 小区 -> 15 ,范围:>=14 <16
  getTypeAndZoom() {
    // 调用地图的 getZoom() 方法,来获取当前缩放级别
    const zoom = this.map.getZoom()
    let nextZoom, type

    // console.log('当前地图缩放级别:', zoom)
    if (zoom >= 10 && zoom < 12) {
      // 区
      // 下一个缩放级别
      nextZoom = 13
      // circle 表示绘制圆形覆盖物(区、镇)
      type = 'circle'
    } else if (zoom >= 12 && zoom < 14) {
      // 镇
      nextZoom = 15
      type = 'circle'
    } else if (zoom >= 14 && zoom < 16) {
      // 小区
      type = 'rect'
    }

    return {
      nextZoom,
      type
    }
  }

  // 创建覆盖物
  createOverlays(data, zoom, type) {
    const {
      coord: { longitude, latitude },
      label: areaName,
      count,
      value
    } = data

    // 创建坐标对象
    const areaPoint = new BMapGL.Point(longitude, latitude)

    if (type === 'circle') {
      // 区或镇
      this.createCircle(areaPoint, areaName, count, value, zoom)
    } else {
      // 小区
      this.createRect(areaPoint, areaName, count, value)
    }
  }

  // 创建区、镇覆盖物
  createCircle(point, name, count, id, zoom) {
    // 创建覆盖物
    const label = new BMapGL.Label('', {
      position: point,
      offset: new BMapGL.Size(-35, -35)
    })

    // 给 label 对象添加一个唯一标识
    label.id = id

    // 设置房源覆盖物内容
    label.setContent(`
      <div class="${styles.bubble}">
        <p class="${styles.name}">${name}</p>
        <p>${count}套</p>
      </div>
    `)

    // 设置样式
    label.setStyle(labelStyle)

    // 添加单击事件
    label.addEventListener('click', () => {
      // 调用 renderOverlays 方法,获取该区域下的房源数据
      this.renderOverlays(id)

      // 放大地图,以当前点击的覆盖物为中心放大地图
      this.map.centerAndZoom(point, zoom)

      // 解决清除覆盖物时,百度地图API的JS文件自身报错的问题
      setTimeout(() => {
        // 清除当前覆盖物信息
        this.map.clearOverlays()
      }, 0)
    })

    // 添加覆盖物到地图中
    this.map.addOverlay(label)
  }

  // 创建小区覆盖物
  /* 
    <div class="${styles.rect}">
      <span class="${styles.housename}">${name}</span>
      <span class="${styles.housenum}">${num}套</span>
      <i class="${styles.arrow}"></i>
    </div>
  */
  createRect(point, name, count, id) {
    // 创建覆盖物
    const label = new BMapGL.Label('', {
      position: point,
      offset: new BMapGL.Size(-50, -28)
    })

    // 给 label 对象添加一个唯一标识
    label.id = id

    // 设置房源覆盖物内容
    label.setContent(`
      <div class="${styles.rect}">
        <span class="${styles.housename}">${name}</span>
        <span class="${styles.housenum}">${count}套</span>
        <i class="${styles.arrow}"></i>
      </div>
    `)

    // 设置样式
    label.setStyle(labelStyle)

    // 添加单击事件
    label.addEventListener('click', () => {
      console.log('小区被点击了')
    })

    // 添加覆盖物到地图中
    this.map.addOverlay(label)
  }

  render() {
    return (
      <div className={styles.map}>
        {/* 顶部导航栏组件 */}
        <NavHeader>地图找房</NavHeader>
        {/* 地图容器元素 */}
        <div id="container" className={styles.container} />
      </div>
    )
  }
}

 运行结果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在微信小程序中使用腾讯地图绘制电子围栏,可以按照以下步骤操作: 1. 在小程序中引入腾讯地图 SDK,并在页面中创建地图实例。 2. 使用腾讯地图提供的 `createCircle` 方法创建一个圆形覆盖物,并设置覆盖物的中心点坐标、半径、线条颜色、填充颜色等属性。 3. 将圆形覆盖物添加到地图中,即可在地图上显示电子围栏。 4. 如果需要动态更新电子围栏的位置或半径,可以通过修改圆形覆盖物的属性实现。例如,调用 `setCenter` 方法更新中心点坐标,调用 `setRadius` 方法更新半径。 下面是一个简单的代码示例,可以在小程序的地图页面中使用: ```javascript // 引入腾讯地图 SDK const QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js'); Page({ data: { map: null, // 地图实例 fence: null, // 电子围栏覆盖物 fenceCenter: { // 电子围栏中心点坐标 latitude: 39.908823, longitude: 116.397470 }, fenceRadius: 500 // 电子围栏半径 }, onLoad: function () { // 创建地图实例 const map = new QQMapWX({ key: 'your_map_api_key' }); // 在页面中创建地图实例 this.setData({ map: map }, () => { // 创建电子围栏覆盖物 const fence = this.data.map.createCircle({ latitude: this.data.fenceCenter.latitude, longitude: this.data.fenceCenter.longitude, radius: this.data.fenceRadius, strokeWidth: 2, strokeColor: '#FF0000', fillColor: '#FF000033' }); // 将电子围栏覆盖物添加到地图中 this.data.map.addOverlay(fence); // 保存电子围栏覆盖物对象 this.setData({ fence: fence }); }); }, // 更新电子围栏的位置和半径 updateFence: function () { // 修改电子围栏覆盖物的属性 this.data.fence.setCenter({ latitude: this.data.fenceCenter.latitude, longitude: this.data.fenceCenter.longitude }); this.data.fence.setRadius(this.data.fenceRadius); } }); ``` 需要注意的是,上述代码中的 `your_map_api_key` 需要替换为你自己的腾讯地图 API 密钥。另外,由于腾讯地图 SDK 的使用方式可能会有所变化,请参考腾讯地图官方文档进行开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值