如何在地图上创建一个覆盖标记,该标记保持在 react-native 的屏幕中心

ati*_*tif 5 javascript css google-maps marker react-native

嘿,我正在尝试添加覆盖标记,即使我们滚动或缩放屏幕,它也会像这样保持在屏幕的中心

在此处输入图片说明

我尝试从其初始位置移动标记,但是当我们快速移动屏幕时它会落后。所以我想在屏幕中央设置标记图像

这是我为移动标记所做的代码:

componentDidMount: function() {
    this.fetchData();
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          region: {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            latitudeDelta: LATITUDE_DELTA,
            longitudeDelta: LONGITUDE_DELTA
          }
        });
      },
    );
    this.watchID = navigator.geolocation.watchPosition((position) => {
      const newRegion = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA
      }

      this.onRegionChange(newRegion);
    });

  },

  componentWillUnmount: function() {
    navigator.geolocation.clearWatch(this.watchID);
  },

  onRegionChange(region) {
    this.setState({ region });
  },
Run Code Online (Sandbox Code Playgroud)

那么如何覆盖标记图像?

mor*_*fer 6

我看到两个选项来解决这个问题:

MapView的方式

只需添加一个 MapView.Marker 与您的区域变量的位置:

  <MapView
    style={styles.map}
    region={this.state.region}
    onRegionChange={this.onRegionChange.bind(this)}>
    <MapView.Marker
      coordinate={{latitude: this.state.region.latitude, longitude: this.state.region.longitude}}
    />
  </MapView>
Run Code Online (Sandbox Code Playgroud)

在我看来,这是“正确”的方式,尽管我面临着这个问题,即标记以很小的延迟更新其位置:当我移动地图时,它相对于地图保持在它的位置上,并且在几百之后它跳回地图中心的毫秒数(非常欢迎有关如何调试或解决此问题的建议)。

第二个选项克服了这个问题

图标方式

将您的 MapView 放在一个视图中,它会填满整个空间。在视图中添加一个居中的图标和您的地图:

<View style={StyleSheet.absoluteFillObject}>
  <Icon name="map-marker" 
    style={{    
      zIndex: 3,
      position: 'absolute',
      marginTop: -37,
      marginLeft: -11,
      left: '50%',
      top: '50%'}} 
    size={40}
    color="#f00" />
  <MapView
    style={StyleSheet.absoluteFillObject}
    region={this.state.region}
    onRegionChange={this.onRegionChange.bind(this)}>
  </MapView>
</View>
Run Code Online (Sandbox Code Playgroud)

请注意使用 zIndex 将其覆盖在 MapView 和 marginTop/marginLeft 前面,可用于将标记的针尖放置在中心。