UNPKG

gmap-ol

Version:

A set of helper classes for working with openLayers.

75 lines (70 loc) 2.71 kB
import GeoJSON from 'ol/format/GeoJSON'; import { Vector as VectorLayer } from 'ol/layer'; import VectorSource from 'ol/source/Vector'; import { getOptionsStyle } from '../MapUtil/MapUtil'; /** * Adds a new vector layer from a geojson file. * * @param {import("ol/Map").default} map the map to add the layer to. * @param {File} file the file to read the geojson from. * @param polygonOptions { * - layerName?: string; * - zIndex?: number; * - visible?: boolean; * - textFieldName?: string; * - styles?: object; * - hoverStyle?: boolean; * } */ function addPolygonLayer(olmap, polygonGeoJSON, polygonOptions) { if (olmap === null || olmap === undefined) { return; // 终止函数执行 } const vectorTileStyle = { fill: { color: 'rgba(255, 255, 255, 0.2)', }, stroke: { width: 1, color: 'rgba(255, 0, 0, 0.5)', }, text: { font: '12px Microsoft YaHei', fill: { color: 'rgba(0, 0, 0, 1)' }, text: '', }, ...polygonOptions.styles, }; const getFeatureStyles = (feature) => { if (polygonOptions.featureColor === undefined || polygonOptions.featureColor !== false) { const fillColor = feature.get('color') || feature.get('COLOR'); if (fillColor) { vectorTileStyle.fill.color = fillColor; } } feature.set('COLOR', vectorTileStyle.fill.color); const textFieldName = polygonOptions.textFieldName ? feature.get(polygonOptions.textFieldName) : ''; if (textFieldName !== '') { vectorTileStyle.text.text = textFieldName; } feature.set('NAME', textFieldName); return getOptionsStyle(vectorTileStyle); }; const vectorLayer = new VectorLayer({ source: new VectorSource({ features: new GeoJSON().readFeatures(polygonGeoJSON), }), zIndex: polygonOptions.zIndex ? polygonOptions.zIndex : 3, visible: polygonOptions?.visible !== undefined && !polygonOptions?.visible ? false : true, style: getFeatureStyles, }); vectorLayer.set('layerName', `${polygonOptions.layerName ? polygonOptions.layerName : ''}`); vectorLayer.set('pickLayerName', `Polygon${polygonOptions.layerName ? polygonOptions.layerName : ''}`); const hoverStyle = polygonOptions?.hoverStyle !== undefined && !polygonOptions?.hoverStyle ? false : true; if (hoverStyle) { vectorLayer.set('tipsLayerName', `tipsLayerName${polygonOptions.layerName ? polygonOptions.layerName : ''}_Polygon`); vectorLayer.set('hoverLayerName', `hoverLayerName${polygonOptions.layerName ? polygonOptions.layerName : ''}_Polygon`); } olmap.addLayer(vectorLayer); } export default addPolygonLayer;