如何通过 react-native-maps 创建一个标记?
How can I create one marker by react-native-maps?
我们可以通过DefaultMarkers创建多个标记,但我只需要一个标记。我需要删除之前的标记并创建新标记。我该怎么做?
我认为其他示例并不比这个更接近我的想法,所以如果您有更好的想法,请告诉我。
let id = 0;
constructor(props){
super(props);
this.state={
markers: [],
}
}
onMapPress(e) {
this.setState({
markers: [
...this.state.markers,
{
coordinate: e.nativeEvent.coordinate,
key: id++,
},
],
});
}
<MapView
style={styles.map}
initialRegion={{
latitude: 28.95761453,
longitude: 50.83710976,
latitudeDelta: 0.0200,
longitudeDelta: 0.0200,
}}
provider={this.props.provider}
onPress={(e) => this.onMapPress(e)}>
{this.state.markers.map(marker => (
<Marker
key={marker.key}
coordinate={marker.coordinate}
/>
))}
</MapView>
只需从 onMapPress 方法中删除 ...this.state.markers 一行并检查输出。如果有任何错误,请告诉我。
onMapPress(e) {
this.setState({
markers: [
{
coordinate: e.nativeEvent.coordinate,
key: id++,
},
],
});
}
我们可以通过DefaultMarkers创建多个标记,但我只需要一个标记。我需要删除之前的标记并创建新标记。我该怎么做?
我认为其他示例并不比这个更接近我的想法,所以如果您有更好的想法,请告诉我。
let id = 0;
constructor(props){
super(props);
this.state={
markers: [],
}
}
onMapPress(e) {
this.setState({
markers: [
...this.state.markers,
{
coordinate: e.nativeEvent.coordinate,
key: id++,
},
],
});
}
<MapView
style={styles.map}
initialRegion={{
latitude: 28.95761453,
longitude: 50.83710976,
latitudeDelta: 0.0200,
longitudeDelta: 0.0200,
}}
provider={this.props.provider}
onPress={(e) => this.onMapPress(e)}>
{this.state.markers.map(marker => (
<Marker
key={marker.key}
coordinate={marker.coordinate}
/>
))}
</MapView>
只需从 onMapPress 方法中删除 ...this.state.markers 一行并检查输出。如果有任何错误,请告诉我。
onMapPress(e) {
this.setState({
markers: [
{
coordinate: e.nativeEvent.coordinate,
key: id++,
},
],
});
}