从How do you center the map on a clicked symbol using MapBox and React Native?上提出的问题继续,我一直在尝试从我的geoJson设置我的activeID(选定功能的ID)的State。又名,当我选择带有特定feature.id的图标时,如何将状态设置为该图标的feature.id。在下面的代码中,activeID是未定义的。谁能告诉我我可能做错了什么?谢谢!
更新:我尝试console.log feature.id(请参见下面的代码),但未定义。由于某种原因,我无法达到目标。
样本功能:
{ “ type”:“ FeatureCollection”, “特征”: [ { “ id”:1 “ type”:“功能”, “属性”:{ “名称”:“酒店” }, “几何”:{ “ type”:“ Point”, “坐标”:[ 12.584664, 55.680532 ] } }
constructor(props) {
super(props);
this.state = {
activeIndex: 0,
activeID: -1,
this.onPress = this.onPress.bind(this);
this.onActiveIndexChange = this.onActiveIndexChange.bind(this);
async onPress(pressFeature) {
const { screenPointX, screenPointY } = pressFeature.properties;
const hitFeatureCollection = await this.map.queryRenderedFeaturesAtPoint(
[screenPointX, screenPointY],
null,
['singleIcon']
);
let feature = null;
let currentFeature = null;
if (hitFeatureCollection.features.length > 0) {
feature = hitFeatureCollection.features[0];
for (let i = 0; i < this.props.featureCollection.features.length; i++) {
currentFeature = this.props.featureCollection.features[i];
console.log(feature.id);
if (feature.id === currentFeature.id) {
this.setState({
activeIndex: i,
isChangeFromPress: true,
destination: feature.geometry.coordinates
});
break;
}
}
}
onActiveIndexChange(index) {
const feature = this.props.featureCollection.features[index];
if (!feature) {
return;
}
this.setState({
activeIndex: index,
activeID: feature.id,
isChangeFromPress: false,
destination: feature.geometry.coordinates
});
}
答案 0 :(得分:1)
短期解决方案将id添加到feature.properties,因此新的geoJson如下所示:
{“ type”:“ FeatureCollection”,“ features”:[{“ id”:1,“ type”:“ Feature”,“ properties”:{“ placeID”:1,“ name”:“ Hotel” },“ geometry”:{“ type”:“ Point”,“ coordinates”:[12.584664,55.680532]}
请让我知道您是否有更好的解决方案!