How to add markers / annotations programatically with mapbox and react native
After chatting directly with Mapbox support, they told me PointAnnotation is legacy and should use ShapeSource and SymbolLayer instead, it have a LOT better performance. Here is how to do it:
<Mapbox.MapView
key='mainmap'
textureMode={true}
pitch={60}
ref={(c) => this._map = c}
onPress={this.onPress}
styleURL={Mapbox.StyleURL.Light}
zoomLevel={17}
maxZoomLevel={20}
minZoomLevel={15}
centerCoordinate={this.initCenterLocation()}
style={{ flex: 1 }}
showUserLocation={true}
userTrackingMode={Mapbox.UserTrackingModes.FollowWithHeading}
>
<Mapbox.ShapeSource
id='exampleShapeSource'
shape={this.state.featureCollection}
onPress={(feature) => this.onShapeSourceLayer(feature)}
images={{ assets: ['pin', 'm1_marker', 'm2_marker', 'm3_marker', 'm4_marker'] }}>
<Mapbox.SymbolLayer id='exampleIconName' minZoomLevel={1} style={stylesIcon.icon} />
</Mapbox.ShapeSource>
</Mapbox.MapView>
Insert new annotations / points:
this.setState({
featureCollection: Mapbox.geoUtils.addToFeatureCollection(
this.state.featureCollection,
Mapbox.geoUtils.makeFeature({ type: 'Point', coordinates: location }, { icon: iconImage, key: key }),
),
});
On annotation Press function:
onShapeSourceLayer(e) {
const feature = e.nativeEvent.payload;
this.setState({
annotationKey: feature.properties.key
}, function () {
this.togglePostModal(true)
});
}
Simple :
constructor() {
this.state = {
myMarker: [0, 0]//intial 0
};
}
<Mapbox.MapView key='mainmap'>
<Mapbox.PointAnnotation
key="key1"
id="id1"
title="Test"
coordinate={this.state.myMarker}>
</Mapbox.PointAnnotation>
</Mapbox.MapVie>
update latitude and longitude :
updateMyMarker(data){
this.setState({myMarker: [data.Lng, data.Lat]})
}