在做关于地图上的论文,要筛选出在多边形内的点,查看了csdn上的一些算法,自己跑了下但是依然有顶点外的点出现,不知道是我的代码哪里出了问题,还望大神指点
1 #我用两个算法都测试了, 2 import csv 3 #第一个测试算法 4 def isInside(lng,lat): 5 #我的6个顶点,下边有图 6 Points=[{"Lat":30.2641546,"Lng":120.1530812}, 7 {"Lat":30.2527681,"Lng":120.1593446}, 8 {"Lat":30.1983117,"Lng":120.1460286}, 9 {"Lat":30.1789750,"Lng":120.0805163}, 10 {"Lat":30.2288384,"Lng":120.0630072}, 11 {"Lat":30.2510622,"Lng":120.0956252} 12 13 ] 14 minlong=120.063007 15 maxlong=120.159344 16 minlat=30.178975 17 maxlat=30.264154 18 #如果被测试点小于最小值,或者大于最大经纬度,那么肯定不在多边形内,直接return false 19 if (lng<minlong or lng>maxlong or lat<minlat or lat>maxlat): 20 return False; 21 count = 6 22 23 result = False; 24 25 j=count-1 26 for i in range(0,count): 27 28 p1 = Points[i]; 29 p2 = Points[j]; 30 31 if(p1["Lat"] < lat and p2["Lat"] >= lat or p2["Lat"] < lat and p1["Lat"] >= lat): 32 33 if(p1["Lng"] + (lat - p1["Lat"]) / (p2["Lat"] - p1["Lat"]) * (p2["Lng"] - p1["Lng"]) < lng): 34 result = not result; 35 j = i; 36 return result; 37 #第二个测试算法 38 # /** 39 # * @description 射线法判断点是否在多边形内部 40 # * @param {Object} p 待判断的点,格式:{ x: X坐标, y: Y坐标 } 41 # * @param {Array} poly 多边形顶点,数组成员的格式同 p 42 # * @return {String} 点 p 和多边形 poly 的几何关系 43 # */ 44 45 def rayCasting(x,y): 46 poly=[{"y":30.2641546,"x":120.1530812}, 47 {"y":30.2527681,"x":120.1593446}, 48 {"y":30.1983117,"x":120.1460286}, 49 {"y":30.1789750,"x":120.0805163}, 50 {"y":30.2288384,"x":120.0630072}, 51 {"y":30.2510622,"x":120.0956252} 52 53 ] 54 px=x 55 py=y 56 flag=False 57 N=6 58 j=N-1 59 for i in range (0,N): 60 sx= poly[i]["x"] 61 sy=poly[i]["y"] 62 tx=poly[j]["x"] 63 ty=poly[j]["y"] 64 if ((sx==px and sy==py) or (tx==px and ty==py) ): 65 return "on" 66 if ((sy<py and ty >= py) or (sy>=py and ty < py)): 67 x=sx+(py-sy)*(tx-sx)/(ty-sy) 68 if (x==px): 69 return "on" 70 if (x>px): 71 flag=not flag 72 j=i 73 74 return flag 75 76 77 78 with open("nearwestlake_state0_2.csv","r") as fr: 79 fr=csv.reader(fr) 80 for row in fr: 81 res=isInside(float(row[1]),float(row[2]))#row[1]是经度,row[2]是纬度 82 print(res) 83 if res==True: 84 fw=open("nearwestlake_2.csv","a") 85 fw.write(','.join(row)+'\n') 86 fw.close() 87 88
下边是我根据算法的三张图,第三张是跑出来以后的结果,右上角总是不对,有个算法是左上角不对,总是跑出顶点范围,感觉我自己的代码有问题,可是我又找不出来,请指点下,毕竟这个点在多边形内问题算是老早的数学问题了,不会是算法的问题,先行感谢了