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

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

项目背景

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

技术栈

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

结论

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

相关推荐
KongHen025 分钟前
uniapp-x实现自定义tabbar
前端·javascript·uni-app·unix
数据潜水员5 分钟前
三层统计最小力度的四种方法
javascript·vue.js
汪子熙6 分钟前
TS2320 错误的本质、触发场景与在 Angular / RxJS 项目中的系统化应对
前端·javascript·angular.js
我命由我1234523 分钟前
React - BrowserRouter 与 HashRouter、push 模式与 replace 模式、编程式导航、withRouter
开发语言·前端·javascript·react.js·前端框架·html·ecmascript
Devin_chen35 分钟前
ES6 Class 渐进式详解
前端·javascript
小番茄夫斯基36 分钟前
前端开发的过程中,需要mock 数据,但是走的原来的接口,要怎么做
前端·javascript
Devin_chen37 分钟前
原型链大白话详解
javascript
英俊潇洒美少年1 小时前
Vue3 的 JSX 函数组件,每次更新都会重新运行吗?
前端·javascript·vue.js
kyriewen2 小时前
Generator 函数:那个能“暂停”的函数,到底有什么用?
前端·javascript·面试
进击的尘埃2 小时前
驾驭Skill市场:从3000+技能包中筛出真正能打的20个
javascript