javascript - 如何更改 react native map 中的标记位置?

标签 javascript reactjs react-native react-native-maps

您好,我想在 map 上添加一个可拖动标记“根据 map View 更改标记的位置” 所以我使用react-native-maps,

当用户滑动 map 并更改其位置时,标记会跟随下摆,因此在我的代码中,我将其记录在控制台中,但我在日志中看不到任何内容,或者它不是以这种方式制作的! 如何使其可在 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;

最佳答案

您可以使用MapViewonRegionChangeComplete 属性来实现此目的。

首先,更改状态对象,如下所示:

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/

相关文章:

react-native - react native : Getting a "there is no route key defined" error

react-native - 如何从 JavaScript 获取 React Native 版本?

Javascript 使用 IF 语句填充数组

javascript - Chart.js 条形图的奇怪问题,图像散射

javascript - 调整谷歌地图大小不起作用并且需要很长时间

javascript - 如何编辑收到的 JSX 元素以将 prop 附加到其中的任何 img 元素?

javascript - 在 Flatlist 项目中 react Native ref。仅返回最后一件商品

javascript - 我如何在 Ext JS 中添加选项卡

javascript - 当用户从 React 的下拉列表中选择一个选项时如何启用另一个输入字段

android - navigator.geolocation.getCurrentPosition 在 React Native 中不起作用