是否可以将自定义 属性 添加到 Openlayers VectorLayer 并稍后在选择功能时访问它?
Is it possible to add custom property to an Openlayers VectorLayer and later access it when a feature is selected?
我正在尝试在初始化图层时将自定义 属性 添加到我的矢量图层,因为源没有我需要的所有数据。
如果我对 API 文档的理解正确,应该是可以的,但我不知道如何 return 在选择功能时自定义 属性 的值地图上的 VectorLayer。
我正在使用以下代码初始化 VectorLayer:
const someVectorLayer = new VectorLayer({
source: new VectorSource({
format: new GeoJSON(),
url: "https://example.com/api/v1/foobar",
}),
customProperty: 'foobar'
});
我正在尝试访问 属性 以设置我的提取 url 以在单击该功能时从正确的位置获取内容:
function onSelect(e) {
const featureValues = e.target.getFeatures().getArray()[0];
const featureId = featureValues.get('id');
const featureCustomProperty = featureValues.get("customProperty");
const fetchUrl = `https://example.com/api/v1/${featureCustomProperty}/${featureId}`;
fetch(fetchUrl)
.then((response) => response.json())
.then((data) => console.log(data));
}
我很感激在这个问题上能得到的任何帮助。显然我还不是 Openlayers 专家。 :)
看起来您使用了错误的变量来访问您的自定义 属性 属性。
selectedFeatureValues 应该是 someVectorLayer
在将要素添加到地图之前使用 loader
设置属性。
var vectorSource = new Vector({
format: new GeoJSON(),
loader: function (extent, resolution, projection) {
var url = '***'
fetch(url).then(data => {
// format data to features , this step depends on your actual situation
const features = new GeoJSON().readFeatures(data)
features.forEach((feature, index) => {
// add a custom properties to feature
feature.setProperties({
index
})
});
vectorSource.addFeatures(features)
})
},
strategy: bbox,
})
function onSelect(e) {
'''
const props = selectedFeature.getProperties()
'''
}
我正在尝试在初始化图层时将自定义 属性 添加到我的矢量图层,因为源没有我需要的所有数据。
如果我对 API 文档的理解正确,应该是可以的,但我不知道如何 return 在选择功能时自定义 属性 的值地图上的 VectorLayer。
我正在使用以下代码初始化 VectorLayer:
const someVectorLayer = new VectorLayer({
source: new VectorSource({
format: new GeoJSON(),
url: "https://example.com/api/v1/foobar",
}),
customProperty: 'foobar'
});
我正在尝试访问 属性 以设置我的提取 url 以在单击该功能时从正确的位置获取内容:
function onSelect(e) {
const featureValues = e.target.getFeatures().getArray()[0];
const featureId = featureValues.get('id');
const featureCustomProperty = featureValues.get("customProperty");
const fetchUrl = `https://example.com/api/v1/${featureCustomProperty}/${featureId}`;
fetch(fetchUrl)
.then((response) => response.json())
.then((data) => console.log(data));
}
我很感激在这个问题上能得到的任何帮助。显然我还不是 Openlayers 专家。 :)
看起来您使用了错误的变量来访问您的自定义 属性 属性。
selectedFeatureValues 应该是 someVectorLayer
在将要素添加到地图之前使用 loader
设置属性。
var vectorSource = new Vector({
format: new GeoJSON(),
loader: function (extent, resolution, projection) {
var url = '***'
fetch(url).then(data => {
// format data to features , this step depends on your actual situation
const features = new GeoJSON().readFeatures(data)
features.forEach((feature, index) => {
// add a custom properties to feature
feature.setProperties({
index
})
});
vectorSource.addFeatures(features)
})
},
strategy: bbox,
})
function onSelect(e) {
'''
const props = selectedFeature.getProperties()
'''
}