天天看點

微信小程式,地圖開發:實作判斷點在面中

傳送門:實作的原理參考

上圖:

微信小程式,地圖開發:實作判斷點在面中

上代碼:

在utils中:

//判斷點是否在面中
function inArea(l, p) {
  var minX = l[0].longitude,
    maxX = l[0].longitude,
    minY = l[0].latitude,
    maxY = l[0].latitude;
  for (var i = 1; i < l.length; i++) {
    if (l[i].longitude < minX) {
      minX = l[i].longitude;
    }
    if (l[i].longitude > maxX) {
      maxX = l[i].longitude;
    }
    if (l[i].latitude < minY) {
      minY = l[i].latitude;
    }
    if (l[i].latitude > maxY) {
      maxY = l[i].latitude;
    }
  }
  if (p.longitude < minX && p.longitude > maxX && p.latitude < minY && p.latitude > maxY) {
    return false // 這個測試都過不了。。。直接傳回false;
  } else {
    var vertx = [],
      verty = [];
    for (var i = 0; i < l.length; i++) {
      vertx.push(l[i].longitude)
      verty.push(l[i].latitude)
    }
    var c = pnpoly(l.length, vertx, verty, p.longitude, p.latitude);
    return c;
  }
}

function pnpoly(nvert, vertx, verty, testx, testy) {
  var i, j, c = false;
  for (i = 0, j = nvert - 1; i < nvert; j = i++) {
    if (((verty[i] > testy) != (verty[j] > testy)) &&
      (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]))
      c = !c;
  }
  return c;
}

module.exports = {
  inArea: inArea,
}
           

在地圖界面中: wxml

<view  class="tbfb">
<map show-location="true" show-compass="true"  style="width: 100%; height:100%"></map>
<map   longitude="{{longitude}}" latitude="{{latitude}}"scale="14"  show-location="true" bindtap="clickMapTap" markers="{{marks}}" 
polygons="{{polygons}}"
bindmarkertap="markertap"  style="width: 100%; height:1200rpx"/>

</view>
           

注意的是bindtap事件,其他的屬性可以參考微信的api

JS:

clickMapTap: function(e) { //單擊地圖事件,在page中作為一個方法的存在。
    //console.log("點選了地圖"
    // if (!false) {
    //   return
    // }
    var mark = new Object();//建立一個mark對象
    mark.id = this.data.marks.length;
    mark.longitude = e.detail.longitude; //經度
    mark.latitude = e.detail.latitude;
    mark.iconPath = "/images/point.png";//點圖示,自己弄
    mark.width = 10;
    mark.height = 12;
//将點選得到的經緯度指派
    var point = {
      longitude: e.detail.longitude,
      latitude: e.detail.latitude
    }
//聲明 fw(範圍)是一個坐标集合,可以自己找一些固定的點。
//(組織形式:[{lat,lng},{lat,lng}...]),
    var inin = util.inArea(fw, point)//條用util中的判斷方法
    mark.label = {
      fontSize: 25,
      anchorX: -5,
      anchorY: 0,
      content: inin ? "在面内" : "在面外",
      textAlign: 'center',
      color: '#000000',
    }
    this.data.marks.push(mark);

    this.setData({//在點選位置設定mark
      marks: this.data.marks,
    })

  },
           

代碼上完了,講下流程,通過綁定地圖的單擊事件,然後判斷點選的點是否在面内!

遇到的坑,1.首先地圖中的polygons是一個面集合,是以不能用面對象直接塞進去,這樣無法顯示面,

2.maker的label是mark的一個對象屬性,直接複制是沒有問題的,

3.setData是用于界面資料更新的方法,是以等于号指派是不起用作的

3.在page的頂端加上var util = require('../../utils/util.js');utils的路徑,來擷取工具類裡面的方法

4.在utils中module.exports是用來映射方法的,是以如果不在裡面添加上你寫的方法是無法使用的

接下來實作了嗎?歡迎提問。

繼續閱讀