您好,我想在 map 上添加一个可拖动标记“根据 map View 更改标记的位置” 所以我使用react-native-maps,
当用户滑动 map 并更改其位置时,标记会跟随下摆,因此在我的代码中,我将其记录在控制台中,但我在日志中看不到任何内容,或者它不是以这种方式制作的! 如何使其可在 map 上拖动?
这是我的代码
import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';
import MapView, {Marker} from 'react-native-maps';
// create a component
class App extends Component {
state = {
latlng: {
latitude: 35.1790507,
longitude: -6.1389008,
},
};
render() {
return (
<View style={styles.container}>
<MapView
style={styles.map}
region={{
latitude: 35.1790507,
longitude: -6.1389008,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
}}>
<Marker
draggable
coordinate={this.state.latlng}
title="Home"
onDragEnd={e => {
console.log('dragEnd', e.nativeEvent.coordinate);
}}
/>
</MapView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
// height: 400,
// width: 400,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
});
//make this component available to the app
export default App;
最佳答案
您可以使用MapView
的onRegionChangeComplete
属性来实现此目的。
首先,更改状态对象,如下所示:
state = {
markerData: {
latitude: 35.1790507,
longitude: -6.1389008,
},
mapData: {
latitude: 35.1790507,
longitude: -6.1389008,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
},
};
相应地更改您的MapView
。
<MapView
style={{flex: 1}}
region={this.state.mapData}
onRegionChangeComplete={this.handleRegionChange}>
<Marker
coordinate={this.state.markerData}
title="Home"
onDragEnd={e => {
console.log('dragEnd', e.nativeEvent.coordinate);
}}
/>
</MapView>
然后定义一个处理函数,当用户在 map 上拖动时更改状态值:
handleRegionChange = mapData => {
this.setState({
markerData: {latitude: mapData.latitude, longitude: mapData.longitude},
mapData,
});
};
希望这有帮助。
关于javascript - 如何更改 react native map 中的标记位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58602029/