[英]OpenLayers place a polygon on the map
我正在為割草機器人防盜設備編寫 Web 應用程序。
我做的第一件事是畫一張地圖,這很有效,結果如下:
圖像 -> https://imgur.com/qJaPZnR.png
接下來我要做的是在地圖上添加一個多邊形,它代表機器人可能所在的區域,在該區域之外會發出警報。 問題是多邊形沒有出現在我的屏幕上,根據 OpenLayers 其面積為 0 :/
這是我的代碼:
function draw_poly(points, style) {
const poly = new ol.geom.Polygon([new ol.geom.LinearRing(points.map(p=>[p.long, p.lat]))], style)
console.log(poly.getArea())
console.log(points.map(p=>[p.long, p.lat]))
return new ol.Feature({
geometry: poly
});
}
[...]
const mower_limit_rect = draw_poly([
{lat: 44.059052, long: 1.344245},
{lat: 44.059022, long: 1.344543},
{lat: 44.058733, long: 1.344482},
{lat: 44.058773, long: 1.344246}
], {
strokeColor: "#00FF00",
strokeOpacity: 1,
strokeWidth: 3,
fillColor: "#00FF00",
fillOpacity: 0.8
});
[...]
const vectorSource = new ol.source.Vector({
features: [mower, mower_limit_rect]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
const map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
view: new ol.View({
center: ol.proj.fromLonLat([14,44]),
zoom: 4
})
});
提前謝謝你!
多邊形應直接從坐標構建,並且必須是封閉的(即最終坐標與第一個坐標相同)。 它還必須從 lon/lat 轉換為視圖投影。 幾何構造函數不接受樣式參數。 您需要根據樣式對象中的值構建 OpenLayers 樣式並將其設置為要素樣式。 單獨的顏色和不透明度值需要組合為 rgba 顏色數組。
function draw_poly(points, style) {
const closedPoints = points.concat([points[0]]);
const poly = new ol.geom.Polygon([closedPoints.map(p=>[p.long, p.lat])]).transform('EPSG:4326', 'EPSG:3857');
const feature = new ol.feature(poly);
const fillColor = ol.color.asArray(style.fillColor).slice();
fillColor[3] = style.fillOpacity;
const strokeColor = ol.color.asArray(style.strokeColor).slice();
strokeColor[3] = style.strokeOpacity;
const olStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: fillColor
}),
stroke: new ol.style.Stroke({
color: strokeColor,
width: style.strokeWidth
})
});
feature.setStyle(olStyle);
return feature;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.