【问题标题】:Remove marker from google map in react native在本机反应中从谷歌地图中删除标记
【发布时间】:2017-05-23 06:51:11
【问题描述】:

是否可以从地图视图中删除标记?如何从谷歌地图视图中删除标记。我使用“react-native-maps”显示谷歌地图。

请帮忙。

【问题讨论】:

  • 你试过什么?显然它与redux(标记)有关?向我们展示一些代码,我们很乐意为您提供帮助。
  • 你能显示到目前为止你尝试过的代码吗?
  • 我正在为此搭桥

标签: react-native react-redux wiki


【解决方案1】:

要能够删除或添加标记,您只需要这样做

//Note : my map markers is => this.props.markers

componentDidMount() {
    this.renderMarkers(this.props.markers)
}


async renderMarkers(mapMarkers) {
    let markers = [];
    markers = mapMarkers.map(marker => (<Marker
            key={marker.code}
            coordinate={{latitude: marker.lat, longitude: marker.lng}}
            onPress={{}}
        />)
    );
    this.setState({markers});
}


refreshMarkers() {
    this.renderMarkers(this.props.markers).then(() => {
        this.forceUpdate();
    });
}


render() {
    return (
        <MapView
            ref={(ref) => this.mapView = ref}
            style={styles.map}
            region={this.props.coordinate}
        >
            {this.state.markers}
        </MapView>
    );
}

【讨论】:

  • 我也将我的标记与状态联系起来,但在我从状态中删除它们后它们仍保留在我的屏幕上
【解决方案2】:

这就是我的做法。 本质上,您需要在状态中保留一组标记,然后从状态中删除要删除的标记。

我将标记列表存储在这样的状态中:

this.state = {
  markers: [],
};

当您实际创建标记时,您将在函数中传递索引,该函数将从状态中删除标记。在这种情况下 onMarkerPress(index)

  createMarkers() {
    return this.state.markers.map((marker, index) => (
      <Marker
        draggable
        onPress={event => this.onMarkerPress(index)}
        key={index}
        coordinate={{
          latitude: parseFloat(marker.latitude),
          longitude: parseFloat(marker.longitude),
        }}
      />
    ));
  }

这是 onMarkerPress 函数:

  onMarkerPress(index) {
    this.state.markers.splice(index, 1);
    this.setState({markers: this.state.markers});
  }

最后,您的地图组件将如下所示:

<MapView
          style={styles.map}
          mapType={'satellite'}
          provider={PROVIDER_GOOGLE}
          initialRegion={{
            latitude: 45.50235905860018,
            longitude: -73.60357092645054,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
          onLongPress={e => this.addNewMarker(e)}>
          {this.createMarkers()}
        </MapView>

就是这样!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2015-04-09
    • 2014-05-01
    • 2013-09-29
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多