微信小程序地图功能开发:绘制多边形和标记点

在微信小程序中,地图功能是一个常见的需求,尤其是在需要展示地理位置、导航指引或区域覆盖的应用中。本文将通过一个实际的微信小程序地图组件示例,介绍如何在地图上绘制多边形区域和标记点,以及如何响应用户的点击事件。

项目背景

本项目的目标是开发一个微信小程序,用于展示和管理泊位信息。用户可以通过点击地图上的不同区域,获取到泊位的详细信息。为了实现这一功能,我们需要在地图上绘制多边形区域,并在每个泊位上放置标记点。

技术栈

  • 微信小程序:腾讯的小程序平台,用于开发轻量级应用。
  • 微信小程序地图组件:微信小程序提供的地图展示和操作组件。
  • gcoord:一个用于坐标转换的JavaScript库,支持不同坐标系之间的转换。

组件实现

这里提供的代码块仅展示了部分关键功能,以帮助读者理解整个实现过程,完整的代码和项目资源可以在个人中心-资源库获取

1. 地图组件模板

在微信小程序中,我们使用<map>组件来承载地图,并设置必要的属性,如纬度、经度、缩放级别等。

html 复制代码
<template>
	<view style="width: 100%;">
		<view class="page-section page-section-gap">
			<!-- subkey:地图密钥  theme="satellite":卫星图模式 -->
			<map class="map-container" :latitude="latitude" 
			:longitude="longitude" :theme="'satellite'" :scale="14"
			:subkey="process.env.VUE_APP_MAP_KEY"  
			@click="onMapTap"
			:markers="markers"
				:polygons="polygonList" theme="satellite">
			</map>
		</view>
	</view>
</template>

2. 脚本逻辑

在脚本部分,我们定义了组件的数据属性,包括地图实例、经纬度、多边形列表和标记点列表。同时,我们实现了一系列的生命周期钩子和方法,用于初始化地图、处理地图点击事件、转换坐标系等。

javascript 复制代码
<script>
import { calculatePolygonCenter, isPointInPolygon } from '@/utils' // 自定义转换工具函数
import gcoord from 'gcoord'  // 地理坐标转换工具
import { apiberthDistribution } from '@/api/berthInfoSearch'

export default {
  data() {
    return {
      map: null,
      latitude: '21.588014',
      longitude: '111.819785',
      polygonList: [],
      markers: [],
      mapKey: '你的微信小程序地图密钥'
    }
  },
  methods: {
    onMapTap(e) {
      const point = { latitude: e.detail.latitude, longitude: e.detail.longitude }
      const area = this.polygonList.find(item => isPointInPolygon(point, item.points))
      if (area) {
        // 跳转到泊位详情页面
      }
    },
    initMap() {
      // 获取泊位数据并初始化地图上的多边形和标记点
    },
    parseStringTo2DArray2(item) {
      // 将字符串形式的坐标转换为二维数组,并计算多边形的中心点,用于标记点
    },
    parseStringTo2DArray(item) {
      // 将字符串形式的坐标转换为二维数组,并创建多边形对象
      let strArr = item.berthCoordinate.split(';').map(item => item.split(','))
	  let ply = []
	  strArr.forEach(item => {
	      let m = this.transitionMap(item[1],item[0])
	      ply.push(m)
	  })
	  let polygon = {
		  id:item.id,
		  points: ply,
		  strokeColor: item.lineColor || '#ceaf93', // 多边形线颜色
		  strokeWidth: 3,
		  fillColor: item.berthColour + 'b3', // 多边形填充颜色
		  zIndex: 11
      }
	  return polygon
    },
    transitionMap(lng, lat) {
      // 转换坐标系
    }
  }
}
</script>

3. 样式定义

为了确保地图能够正确显示,我们定义了地图容器的样式,设置了其高度和宽度。

css 复制代码
<style lang="scss" scoped>
.map-container {
  height: 100vh;
  width: 100vw;
}
</style>

4. 坐标转换

为了确保地图上显示的坐标准确,我们使用了gcoord库和自定义的转换函数来处理坐标系的转换。

javascript 复制代码
/**
 * 判断点是否在某多边形闭合区域内
 * @typedef Point
 * @property {number} latitude
 * @property {number} longitude
 * @param {Point} point 坐标点
 * @param {Point[]} polygon 多边形坐标
 * @returns {boolean}
 */
export const isPointInPolygon = (point, polygon) => {
  let xi, xj, yi, yj
  let inside = false

  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    xi = polygon[i].longitude
    yi = polygon[i].latitude
    xj = polygon[j].longitude
    yj = polygon[j].latitude

    /* 如果点在多边形的顶点上,直接返回 true */
    if ((xi === point.longitude && yi === point.latitude) || (xj === point.longitude && yj === point.latitude)) {
      return true;
    }

    /* 如果点在多边形的边界上,也返回 true */
    if (yi > point.latitude != yj > point.latitude && point.longitude <= (xj - xi) * (point.latitude - yi) / (yj - yi) + xi) {
      inside = !inside
    }
  }

  return inside
}

/**
 * 获取多边形闭合区域中心点坐标
 * @param {Point[]} polygon 多边形坐标
 * [{latitude: 21.5727777646496, longitude: 111.82918938585996},
    {latitude: 21.572896900539284, longitude: 111.82948384286787},
    {latitude: 21.573441024780955, longitude: 111.82921084053669},
    {latitude: 21.573281991421084, longitude: 111.8289163807698}]
 * @returns {latitude,longitude}
 */
export const calculatePolygonCenter = vertices => {
  let totalLatitude = 0
  let totalLongitude = 0
  vertices.forEach(vertex => {
    totalLatitude += vertex.latitude
    totalLongitude += vertex.longitude
  })
  const centerLatitude = totalLatitude / vertices.length
  const centerLongitude = totalLongitude / vertices.length
  return { latitude: centerLatitude, longitude: centerLongitude }
}

结论

通过本文的介绍,我们了解了如何在微信小程序中集成地图功能,并在地图上绘制多边形区域和标记点。这为开发具有地理位置展示和交互功能的应用提供了一个实用的解决方案。随着微信小程序平台的不断更新和扩展,我们可以期待未来能够实现更多创新的地图功能和交互体验。

相关推荐
持续升级打怪中4 分钟前
ES6 Promise 完全指南:从入门到精通
前端·javascript·es6
毕设源码-郭学长9 分钟前
【开题答辩全过程】以 酒店预约微信小程序为例,包含答辩的问题和答案
微信小程序·小程序
wulijuan88866610 分钟前
Web Worker
前端·javascript
老朋友此林21 分钟前
React Hook原理速通笔记1(useEffect 原理、使用踩坑、渲染周期、依赖项)
javascript·笔记·react.js
克里斯蒂亚诺更新23 分钟前
vue3使用pinia替代vuex举例
前端·javascript·vue.js
冰暮流星38 分钟前
javascript赋值运算符
开发语言·javascript·ecmascript
西凉的悲伤1 小时前
html制作太阳系行星运行轨道演示动画
前端·javascript·html·行星运行轨道演示动画
低保和光头哪个先来2 小时前
源码篇 实例方法
前端·javascript·vue.js
你真的可爱呀2 小时前
自定义颜色选择功能
开发语言·前端·javascript
小王和八蛋2 小时前
JS中 escape urlencodeComponent urlencode 区别
前端·javascript