在React Native Maps中渲染多个标记

20

嗨,我是React Native的新手,想问一下如何在地图中渲染多个标记。

这是我的代码:

类内部:

constructor(props) {
super(props);

  this.state = {
   coordinate: ([{
     latitude: 3.148561,
     longitude: 101.652778,
     title: 'hello'
   },
   {
     latitude: 3.149771,
     longitude: 101.655449,
     title: 'hello'
   }
  ]),
 };

}

在render内部:

<MapView
        style={styles.map}
        showsUserLocation={true}
        followUserLocation={true}
        zoomEnabled={true}
        //annotations={markers}
      >  
            <MapView.Marker
              coordinate={this.state.coordinate}
              title={this.state.coordinate.title}
            />
      </MapView>

我想在地图上显示这两个标记,但我还不知道如何在React Native中制作循环以将它们渲染出来。我已经尝试文档中的内容,但仍然无法工作。

预先感谢您:)

1个回答

49

coordinate 属性构造不正确。请像这样做 -

this.state = {
  markers: [{
    title: 'hello',
    coordinates: {
      latitude: 3.148561,
      longitude: 101.652778
    },
  },
  {
    title: 'hello',
    coordinates: {
      latitude: 3.149771,
      longitude: 101.655449
    },  
  }]
}

在渲染函数中

<MapView 
  ....
>
  {this.state.markers.map(marker => (
    <MapView.Marker 
      coordinate={marker.coordinates}
      title={marker.title}
    />
  ))}
</MapView>

1
谢谢!之前我对于如何构建坐标的属性有些误解,因为我是按照React Native中的MapView来操作的。再次感谢你,你真的帮了我很多:)祝你有愉快的一天^_^ - Hazim Ali
5
由于某种原因,这段精确的代码对我来说不起作用。 - Francis
2
对我来说,我必须添加一个“索引”和“键”。 {this.state.markers.map((marker, index) => ( <MapView.Marker key={index} coordinate={marker.coordinates} title={marker.title} /> ))} - Ryan Walker
它已经解决了多个标记问题。谢谢。 - Jagdish Bhavsar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接