首页 > 解决方案 > 如何将 activeID 的状态设置为 React Native 中 MapBox 上选定图标的特定 feature.id

问题描述

如何使用 MapBox 和 React Native 将地图居中于单击的符号上?,我一直在尝试从我的 geoJson 中设置我的 activeID(我选择的功能的 id)的状态。Aka,当我选择具有特定 feature.id 的图标时,如何将状态设置为该图标的 feature.id。在我下面的代码中,activeID 是未定义的。谁能告诉我我可能做错了什么?谢谢!

更新:我试图 console.log feature.id (见下面的代码),我得到了未定义的。由于某种原因,我无法达到它。

样品特点:

{ "type": "FeatureCollection", "features": [ { "id": 1, "type": "Feature", "properties": { "name": "Hotel" }, "geometry": { "type ": "点", "坐标": [ 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
        });
}

标签: javascriptreact-nativefor-loopmapbox

解决方案


短期解决方案是向 feature.properties 添加一个 id,所以新的 geoJson 看起来像这样:

{“类型”:“FeatureCollection”,“功能”:[{“id”:1,“类型”:“功能”,“属性”:{“placeID”:1,“名称”:“酒店”},“几何”:{“类型”:“点”,“坐标”:[12.584664, 55.680532] } }

如果您有更好的解决方案,请告诉我!


推荐阅读