Reputation: 13
I used react-native-maps in my location tracking application. And now i want to clear ( refresh ) the map with all the markers and poly-lines without refreshing react component , when user stop the location Tracking ( using a button ).Is there any way to do that?
Upvotes: 1
Views: 6663
Reputation: 499
At some point if you wish to change what is visible on your component in react, there's no other way than rerendering your component.
I do not know react-native-maps
, but I think this problem can be solved using general react knowledge.
Markers and polygons in react-native-maps
are added as children of the MapView
, so depending on how you are storing your markers/lines, you should be able to simply rely on react's state or props changes to update your MapView
.
For example, if your markers are stored in your component's state, you could do something like this:
class MyLocationTracker extends React.Component {
state = { markers: [{ latlng: { latitude: 1, longitude: 1 } }] }
render = () => {
return (
<View>
<Text onPress={() => this.setState({ markers: [] })}>Reset markers</Text>
<MapView>
{this.state.markers.map((marker) => <Marker coordinate={marker.latlng} />)}
</MapView>
</View>
)
}
}
When the state
changes, react will call the render()
function again and update the markers. Note that this will also serenader the <MapView />
component.
If you wish to avoid rerendering the <MapView />
component, you can move the logic to a new component that will handle the markers only, like so:
class MyLocationTracker extends React.Component {
render = () => {
return (
<View>
<Text onPress={this.markers.reset}>Reset markers</Text>
<MapView>
<MyMarkers ref={(comp) => { this.markers = comp }} />
</MapView>
</View>
)
}
}
class MyMarkers extends React.Component {
state = { markers: [{ latlng: { latitude: 1, longitude: 1 } }] }
reset = () => {
this.setState({ markers: [] })
}
render = () => {
return (
<View>
{this.state.markers.map((marker) => <Marker coordinate={marker.latlng} />)}
</View>
)
}
}
Again, changes in the state would trigger a rerender of your component. But now, since only <MyMarkers />
's state changes, it will rerender itself but not anything else.
I hope that helps :)
Upvotes: 1