I am fetching coordinates from my database every 5 seconds, and my marker is dynamic, this is my render method
console.log('render'+this.state.driverLocation.latitude +' '+this.state.driverLocation.longitude);
let marker = null;
marker = <MapView.Marker title='This is you' coordinate={this.state.driverLocation } />;
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
region={!this.state.locationChosen ? this.state.focusedLocation : null}
style={styles.map}
onPress={this.pickLocationHandler}
ref={ref => this.map = ref}
>
{marker}
</MapView>
The log statement in render shows driverLocation changes every 5 sec as it should but the marker stays at the initial position (coordinates given while defining state).
Is there any problem with my code? Do I need to add something? Any help would be appreciated.
The problem was that android relies only on the key to change in order to update the custom marker and it can be solved by assigning a random key to the marker every time there's a need for rerendering.
So, something like this:
marker = <MapView.Marker
title='This is you'
coordinate={this.state.driverLocation}
key={ this.GenerateRandomNumber() }
} />;
While:
GenerateRandomNumber=()=>
{
var RandomNumber = Math.floor(Math.random() * 100) + 1 ;
return RandomNumber;
}
Related
Using "react-native-pager-view": "^6.1.2" package in ReactNative.
I have the same bug as here.
https://github.com/callstack/react-native-pager-view/issues/503
I'm trying PagerView with the code pasted below, but when I swipe to move the page, e.nativeEvent.position is different from the actual page index.
import PagerView, { PagerViewOnPageScrollEvent, PagerViewOnPageSelectedEvent } from 'react-native-pager-view';
import Modal from 'react-native-modal';
const onPageScroll = useCallback((e: PagerViewOnPageScrollEvent) => onPageScrollPagerView(e, setCurrentTabIndex), []);
const onPageScrollPagerView = (
e: PagerViewOnPageScrollEvent,
setCurrentTabIndex: React.Dispatch<React.SetStateAction<number>>,
) => {
console.log(`onPageScroll position = ${e.nativeEvent.position}`);
setCurrentTabIndex(e.nativeEvent.position);
};
return (
<Modal isVisible={isVisible}>
<SafeAreaView>
<View>
<PagerView ref={viewPager} initialPage={0} onPageScroll={onPageScroll} onPageSelected={onPageSelected}>
{list.map((item) => (
<View key={item.id}>
{item.content}
</View>
))}
</PagerView>
</View>
</SafeAreaView>
</Modal>
);
This is the result obtained when scrolling to the first page.
onPageScroll is called twice, and for some reason the wrong position is returned the second time.
And 0 is set to setCurrentTabIndex.
onPageScroll position = 1
onPageScroll position = 0
Is there any way to resolve this?
It may be related to what you write in <Modal></Modal> of 'react-native-modal'.
As also written here, this problem does not occur on iPhone11, but on iPhone12 and newer devices.
I didn't use 'react-native-modal', I used fullscreen modal.
screenOptions={{ presentation: 'modal' }}
I would like to create a scrollable FlatList to select only one item among a list. After the user scroll the list, the selected item will be the one in the colored rectangle (which have a fixed position) as you can see here :
Actually I'm only able to render a basic FlatList even after some researches.
Do you know how I should do that ?
I found the solution (but it's not a FlatList) !
To do that I use :
https://github.com/veizz/react-native-picker-scrollview.
To define the background of the current selected items I added a new props highLightBackgroundColor in the ScrollPicker Class in the index file of react-native-picker-scrollview :
render(){
...
let highLightBackgroundColor = this.props.highLightBackgroundColor || '#FFFFFF';
...
let highlightStyle = {
...
backgroundColor: highLightBackgroundColor,
};
...
How to use it :
<ScrollPicker
ref={sp => {
this.sp = sp;
}}
dataSource={['a', 'b', 'c', 'd', 'e']}
selectedIndex={0}
itemHeight={50}
wrapperHeight={250}
highLightBackgroundColor={'lightgreen'}
renderItem={(data, index, isSelected) => {
return (
<View>
<Text>{data}</Text>
</View>
);
}}
onValueChange={(data, selectedIndex) => {
//
}}
/>
How it looks without others customizations:
You can implement the same setup with the very popular react-native-snap-carousel package, using the vertical prop. No need to use a smaller, poorly documented/unmaintained package for this.
I have a FlatList as shown below:
<FlatList
inverted
data={messages}
keyExtractor={this._keyExtractor}
renderItem={({ item }) => (
<Text style={styles.item}>{item}</Text>
)}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={30}
/>
But here the OnEndReached method does not gets called when I reach the top of the flatlist.
Please help
OnEndReachedThreshold must be a number between 0 and 1. Since you are inverting your flatlist, onEndReachedThreshold would be the distance the user is from the top of the list [in percents]. Therefore a value of 0.5 would trigger the OnEndReached function when the user has scrolled through 50% of the viewable list.
To trigger the function at 50% your code should read something like this:
<FlatList
inverted
data={messages}
keyExtractor={this._keyExtractor}
renderItem={({ item }) => (
<Text style={styles.item}>{item}</Text>
)}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={0.5}
/>
All I could figure out was using of onScroll (performance beware) in here: https://snack.expo.io/#zvona/inverted-list-onbeginreached
The actual function looks like this:
checkIfBeginningReached = ({ nativeEvent }) => {
const { layoutMeasurement, contentOffset } = nativeEvent;
const currentPos = layoutMeasurement.height + contentOffset.y;
const listLength = ITEM_HEIGHT * this.state.items.length;
const reactThreshold = listLength - (ITEM_HEIGHT * THRESHOLD);
if (currentPos >= reactThreshold) {
this.fetchMoreItems(this.state.items.length);
}
}
On that, we pick up necessary info from nativeEvent (which kind of holds everything relevant). Then we just calculate the current position in pixels, length of whole list content in pixels and then threshold point.
In all, this particular solution requires two things:
1) list has fixed and same size of elements
2) list is not multi-column.
All the other functionality in the demo is just faking / mimicking one use case (of fetching 50 more items from server with 500ms delay). But I'll improve my answer if possible. But this should get you started.
My solution is here:
isCloseToBottom = ({layoutMeasurement, contentOffset, contentSize}) => {
const paddingToBottom = 1
return layoutMeasurement.height + contentOffset.y >=
contentSize.height - paddingToBottom}
just set onEndReachedThreshold={0.1} or onEndReachedThreshold={0.2}
In a react-native app usig react-native-maps, I'm trying to programmatically show the MapView.Callout of a specific MapView.Marker amongst many. I'm planning to use the showCallout-method, but haven't yet found out how to access all of the MapView's markers, from where I could select the correct one based on it's id/key/ref.
The markers are rendered onto the MapView in a map-loop as below.
Sofar I've tried without success to get hold of all the MapView's markers using this.refs.mapView.refs / this.refs.mapView.children but I don't get anything there.
<MapView>
ref={'mapView'}
...
>
{this.props.screenProps.appState.cachedDeviations.map(deviation => {
return (
<MapView.Marker
coordinate={
deviation.position
}
key={deviation.Id}
ref={deviation.Id}
>
<MapView.Callout style={styles.callout}>
<DeviationCallout
...
/>
</MapView.Callout>
</MapView.Marker>
)
})
}
</MapView>
Any hints?
You can use functional ref.
Example
<MapView.Marker
coordinate={ deviation.position }
key={deviation.Id}
ref={(ref) => this.markers[deviation.Id] = ref}
>
// ...
</<MapView.Marker>
// ...
this.markers[someId].showCallout();
I use the great react-native-maps from Airbnb on a react-native app.
I got a list of markers on a JSON file where each of these markers have a property zoom which is a integer of an approximate zoom level where the marker should display / hide on the map.
Is there a way based on the latitudeDelta and longitudeDelta of a Region to get an approximate double/integer of the current zoom level as we have on Google Maps (1 to 20) ?
Thanks
Ok I come with an handy solution, I don't know if we can do better.
I added the onRegionChange event to retrieve the region, then I use some math :
<MapView
style={styles.map}
initialRegion={this.state.region}
onRegionChange={region => {
clearTimeout(this.timerForMap)
this.timerForMap = setTimeout(() => {
this.showMarkers(region)
}, 100)
}}>
...
Then :
showMarkers(region) {
let zoom = Math.round(Math.log(360 / region.longitudeDelta) / Math.LN2)
...
}
If someone have a better way to do it, feel free to comment !
Thanks.
you can get the zoom level from getCamera() using onRegionChange in MapView
const [zoom, setZoom] = useState(''); //initiates variable zoom
const getZoom = async () => {
const coords = await mapRef.getCamera();
setZoom(coords.center.zoom); // sets variable zoom the value under coords.center.zoom
}
<MapView>
ref = {(ref) => mapRef = ref}
onRegionChange = {() => {getZoom();}}
</MapView>