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

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

项目背景

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

技术栈

  • 微信小程序:腾讯的小程序平台,用于开发轻量级应用。
  • 微信小程序地图组件:微信小程序提供的地图展示和操作组件。
  • 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 }
}

结论

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

相关推荐
candyTong1 天前
一觉醒来,大模型就帮我排查完页面性能问题
前端·javascript·架构
玩嵌入式的菜鸡1 天前
网页访问单片机设备---基于mqtt
前端·javascript·css
前端一小卒1 天前
我用 Claude Code 的 Superpowers 技能链写了个服务,部署前差点把服务器搞炸
前端·javascript·后端
好赞科技1 天前
深度测评2026年精选美发预约小程序排行榜 革新预约新体验 修订
大数据·微信小程序
豹哥学前端1 天前
用猜数字游戏,一口气掌握 JavaScript 核心知识点(附完整代码)
前端·javascript
忆往wu前1 天前
从0到1一步步拆解搭建,梳理一个 Vue3 简易图书后台全开发流程
前端·javascript·vue.js
shao9185161 天前
第3章(2)——使用Gradio JavaScript Client
javascript·node.js·cdn·gradio·job·events·playcode
光影少年1 天前
大屏页面,一次多个请求,请求加密导致 点击 全局时间选择器 时出现卡顿咋解决(面板收起会延迟1~2秒)
前端·javascript·vue.js·学习·前端框架·echarts·reactjs
Mr.mjw1 天前
vue中封装一个环形进度条组件,根据外部盒子大小自适应变化
前端·javascript·vue.js
无心使然1 天前
Openlayers调用ArcGis影像服务之一动态地图、地图切片(/exportImage)
前端·javascript·数据可视化