Feature 类型

在 OpenLayers 中,Feature(要素)是表示地图上地理实体的核心对象,它结合了几何形状(Geometry)和属性数据(Attributes),是地图上可视化和交互的基本单元。下面详细介绍 OpenLayers 中的 Feature 类型。

OpenLayers 支持多种几何类型,常用的有:

  • Point:点

  • LineString:线

  • Polygon:面

  • MultiPoint:多点

  • MultiLineString:多线

  • MultiPolygon:多面

  • Circle:圆

  • GeometryCollection:几何集合

Feature 的常见方法:

方法描述
getId()获取要素的唯一标识符
setId(id)设置要素的唯一标识符
get(key)获取指定键的属性值
set(key, value)设置属性值
setProperties(props)批量设置属性
getGeometry()获取要素的几何对象
setGeometry(geom)设置要素的几何对象
getStyle()获取要素的样式(或样式函数)
setStyle(style)设置要素的样式(可以是样式对象或返回样式的函数)
on(event, listener)监听要素事件(如 changepropertychange

创建 Feature 对象

创建点要素(Point)

import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';

const pointFeature = new Feature({
    geometry: new Point([116.39, 39.9]), // 坐标:[经度, 纬度]
    name: '北京市',
    population: 21540000
});

创建线要素(LineString)

import LineString from 'ol/geom/LineString';

const lineFeature = new Feature({
    geometry: new LineString([
        [116.39, 39.9],
        [121.47, 31.23],
        [113.27, 23.13]
    ]),
    name: '主要城市连接线'
});

创建面要素(Polygon)

import Polygon from 'ol/geom/Polygon';

const polygonFeature = new Feature({
    geometry: new Polygon([[
        [116.39, 39.9],
        [121.47, 31.23],
        [113.27, 23.13],
        [116.39, 39.9] // 闭合环
    ]]),
    name: '三角形区域',
    area: 10000 // 面积(示例属性)
});

Feature 的属性操作

获取和设置属性

// 获取属性
const name = pointFeature.get('name'); // "北京市"

// 设置属性
pointFeature.set('population', 22000000);
pointFeature.setProperties({
    population: 22000000,
    capital: true
});

获取几何形状

const geometry = pointFeature.getGeometry(); // 返回 Point 对象
const type = geometry.getType(); // 返回 "Point"
const coordinates = geometry.getCoordinates(); // 返回 [116.39, 39.9]

const features = source.getFeatures(); // 获取所有要素
const featureAtCoordinate = source.getFeaturesAtCoordinate([116.39, 39.9]);

四下皆无人