# openlayer 繪製多邊形
阿新 • • 發佈:2022-03-28
openlayer 繪製多邊形
/*** 繪製多邊形 points:多邊形頂點組成的列表 */ drawPolygon(points) { let layer = this.getLayerFromMap(this.map, 'polygon') // 先檢視一下之前是否存在,如果存在先移除 if (layer) { this.map.removeLayer(layer) } let features = [] var polygon = new Polygon([points]) var feature = new Feature(polygon) features.push(feature) var vectorSource = new VectorSource() vectorSource.addFeatures(features) const styleFunction = function (feature) { return new Style({ fill: new Fill({ color: [255, 255, 255, 0.33] }), stroke: new Stroke({ width: 2, color: '#dc5246' }), text: new Text({ font: '10px Microsoft YaHei', text: '多邊形', overflow: true, textAlign: 'center', // 對齊方式 textBaseline: 'middle', // 文字基線 fill: new Fill({ color: '#0e84ba' }), offsetX: 0 }) }) } var vlayer = new VectorLyr({ title: 'polygon', source: vectorSource, style: styleFunction }) this.map.addLayer(vlayer) },
獲取地圖是否存在圖層的函式。
// 根據圖層title獲取地圖圖層,如果有就返回圖層,沒有就返回null getLayerFromMap(map, name) { var layers = map.getLayers() // 獲取地圖所有圖層 var layer = null layers.forEach((item, index) => { if (item.values_.title !== undefined) { if (item.values_.title === name) { layer = item return layer } } }) return layer }