最近在工作中遇到了這個一個需求,用戶設定地理圍欄,后台獲取到實時位置信息后通過與圍欄比較,判斷是否越界等。
這個過程需要用到數據協議為GEOjson,通過查閱資料后,發現python的shapely庫可以非常簡單的解決這個問題,接下來演示一下我處理這個問題的過程。
測試數據:
通過http://geojson.io/來獲得測試數據,如下圖,在地圖上繪制了一個多邊形設為地理圍欄,分別取了圍欄內外兩個點來進行測試。
得到GEOjson數據如下:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
114.3458104133606,
30.476167529462785
],
[
114.34512376785278,
30.475575748963195
],
[
114.34576749801636,
30.474540124433936
],
[
114.3467652797699,
30.475363076967565
],
[
114.34693694114685,
30.476102803645833
],
[
114.3458104133606,
30.476167529462785
]
]
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
114.34605717658997,
30.475584995561178
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
114.346604347229,
30.476518897432545
]
}
}
]
}
安裝shapely
本測試基於python——python3.6
$ pip install shapely
windows安裝shapely會報錯
shapely解析地理圍欄
話不多說直接上代碼
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))
下面是實際的實例:
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
polygon_data= [
[
114.3458104133606,
30.476167529462785
],
[
114.34512376785278,
30.475575748963195
],
[
114.34576749801636,
30.474540124433936
],
[
114.3467652797699,
30.475363076967565
],
[
114.34693694114685,
30.476102803645833
],
[
114.3458104133606,
30.476167529462785
]
]
point1 = Point([114.34605717658997,30.475584995561178])
point2 = Point([114.346604347229,30.476518897432545])
polygon = Polygon(polygon_data)
print(polygon.contains(point1))
print(polygon.contains(point2))
輸出結果:
True
False
這樣一來我們就快速的實現了,目標點是否在地理圍欄內的判斷。
總結
Python還是挺好用的:)