How to display user location in reactive native maps and expo - react-native

I have the user's location but I can't seem to display it on the map, here's my code:
useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
})();
}, []);
let text = 'Waiting..';
if (errorMsg) {
text = errorMsg;
} else if (location) {
text = JSON.stringify(location);
}
let userLatitude = text.latitude
let userLongitude = text.longitude
return (
<View style={styles.layout}>
<MapView style={styles.map}>
<MapView.Marker
coordinate={{latitude: userLatitude,
longitude: userLongitude}}
title={"title"}
description={"description"}
/>
</MapView>
</View>
);
I got most of my code off of the expo location documentation, so I don't know what I'm doing wrong.

There is nothing in these variables
let userLatitude = text.latitude // undefined
let userLongitude = text.longitude // undefined
Location.getCurrentPositionAsync() returns object:
Object {
"coords": Object {
"accuracy": 5,
"altitude": 0,
"altitudeAccuracy": -1,
"heading": -1,
"latitude": 47.0448,
"longitude": 37.976,
"speed": -1,
},
"timestamp": 1659337371953.4102,
}
Working code example:
export default function App() {
const [userLocation, setUerLocation] = useState(null);
useEffect(() => {
(async () => {
// ... persmissions check
const location = await Location.getCurrentPositionAsync();
setUerLocation(location);
})()
}, [])
return (
<View style={styles.container}>
<MapView style={{width: '100%', height: '100%'}}>
{userLocation && <Marker coordinate={userLocation.coords} />}
</MapView>
</View>
);
}

if you have the user's foreground permission, you can see the location of the user directly inside the MapView component. There is a showsUserLocation prop that defaults to false. Set that to true and it should show up (fingers crossed ;).
return (
<View style={styles.layout}>
<MapView style={styles.map}
showsUserLocation={true}
followsUserLocation={true}
>
// (markers, geojson etc go here)
</MapView>
</View>
);

Related

Styling camera on React native

On a screen, I want to scan tickets this way :
class Tickets extends Component {
constructor(props) {
super(props);
this.state = {
Press: false,
hasCameraPermission: null,
reference: '',
lastScannedUrl:null,
displayArray: []
};
}
initListData = async () => {
let list = await getProductByRef(1);
if (list) {
this.setState({
displayArray: list,
reference: list.reference
});
}
console.log('reference dans initListData =', list.reference)
};
async UNSAFE_componentWillMount() {
this.initListData();
console.log('reference dans le state =', this.state.reference)
};
componentDidMount() {
this.getPermissionsAsync();
}
getPermissionsAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === "granted" });
};
_onPress_Scan = () => {
this.setState({
Press: true
});
}
handleBarCodeScanned = ({ type, data }) => {
this.setState({ Press: false, scanned: true, reference: data });
this.props.navigation.navigate('ProductDetails', {reference : parseInt(this.state.state.reference)})
};
renderBarcodeReader = () => {
const { hasCameraPermission, scanned } = this.state;
if (hasCameraPermission === null) {
return <Text>{i18n.t("scan.request")}</Text>;
}
if (hasCameraPermission === false) {
return <Text>{i18n.t("scan.noaccess")}</Text>;
}
return (
<View
style={{
flex: 1,
...StyleSheet.absoluteFillObject
}}
>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned}
style={{ flex:1, ...StyleSheet.absoluteFillObject}}
/>
{scanned && (
<Button
title={"Tap to Scan Again"}
onPress={() => this.setState({ scanned: false })}
/>
)}
</View>
);
}
render() {
const { hasCameraPermission, scanned, Press } = this.state;
let marker = null;
console.log('displayArray', this.state.displayArray, 'reference', this.state.displayArray.reference)
return (
<View style={{flex:1}}>
<KeyboardAvoidingView behavior="padding" enabled style={{flex:1}}>
<ScrollView contentContainerStyle={{flexGrow: 1 }} >
{Press ? (
<View style={{flex:1}}>
{this.renderBarcodeReader()}
</View>
) : (
<View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
<Button
color="#F78400"
title={i18n.t("scan.scan")}
onPress={this._onPress_Scan}>
</Button>
</View>
)}
</ScrollView>
</KeyboardAvoidingView>
</View>
);
}
}
export default Tickets;
This code gives me
As you can see I have a top and bottom margin. I would like there to be no space, for the camera to take the entire screen (and for any buttons to be displayed over the camera image)
How can I do it, the style of which element should I change?
Thanks for any help and explanations
can you leave your code for that part? now everything is okay but i believe the image width and height is static and you are not using resizeMode for that image, for camera it will be different .
you can check resizeMode for the camera library you are using

improving elements styles to make a full screen scan

I will need a helping hand to edit this page. i have all the elements but i need help styling.
I would like to have the camera (the image you see is the typical emulator camera, that's why it makes an image) in full screen and from above at the top, the message in red and the 'autocomplete.
If you want, to explain better, I would like to respect the image below: autocomplete at the top left above the camera in full screen.
would it be possible for you to help me, I'm getting a little confused. I tried to do a snack but failed. I will add it later if i can.
const autocompletes = [...Array(10).keys()];
const apiUrl = "https://5b927fd14c818e001456e967.mockapi.io/branches";
class Tickets extends Component {
constructor(props) {
super(props);
this.state = {
Press: false,
hasCameraPermission: null,
reference: '',
lastScannedUrl:null,
displayArray: []
};
}
initListData = async () => {
let list = await getProductByRef(1);
if (list) {
this.setState({
displayArray: list,
reference: list.reference
});
}
// console.log('reference dans initListData =', list.reference)
};
async UNSAFE_componentWillMount() {
this.initListData();
// console.log('reference dans le state =', this.state.reference)
};
componentDidMount() {
this.getPermissionsAsync();
}
getPermissionsAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === "granted" });
};
_onPress_Scan = () => {
this.setState({
Press: true
});
}
handleBarCodeScanned = ({ type, data }) => {
this.setState({ Press: false, scanned: true, reference: data });
this.props.navigation.navigate('ProductDetails', {reference : parseInt(this.state.state.reference)})
};
renderBarcodeReader = () => {
const { hasCameraPermission, scanned } = this.state;
if (hasCameraPermission === null) {
return <Text>{i18n.t("scan.request")}</Text>;
}
if (hasCameraPermission === false) {
return <Text>{i18n.t("scan.noaccess")}</Text>;
}
return (
<View
style={{
flex: 1,
...StyleSheet.absoluteFillObject
}}
>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned}
style={{ flex:1, height:'100%', ...StyleSheet.absoluteFillObject}}
/>
{scanned && (
<Button
title={"Tap to Scan Again"}
onPress={() => this.setState({ scanned: false })}
/>
)}
</View>
);
}
handleSelectItem(item, index) {
const {onDropdownClose} = this.props;
onDropdownClose();
console.log(item);
}
render() {
const { hasCameraPermission, scanned, Press } = this.state;
let marker = null;
const {scrollToInput, onDropdownClose, onDropdownShow} = this.props;
// console.log('displayArray', this.state.displayArray, 'reference', this.state.displayArray.reference)
return (
<View style={styles.container}>
{Press ? (
<View style={{flex:1}}>
<View style={styles.dropdownContainerStyle}>
<Autocomplete
key={shortid.generate()}
containerStyle={styles.autocompleteContainer}
inputStyle={{ borderWidth: 1, borderColor: '#F78400'}}
placeholder={i18n.t("tickets.warning")}
pickerStyle={styles.autocompletePicker}
scrollStyle={styles.autocompleteScroll}
scrollToInput={ev => scrollToInput(ev)}
handleSelectItem={(item, id) => this.handleSelectItem(item, id)}
onDropdownClose={() => onDropdownClose()}
onDropdownShow={() => onDropdownShow()}
fetchDataUrl={apiUrl}
minimumCharactersCount={2}
highlightText
valueExtractor={item => item.name}
rightContent
rightTextExtractor={item => item.properties}
/>
</View>
{this.renderBarcodeReader()}
</View>
) : (
<View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
<Button
color="#F78400"
title={i18n.t("scan.scan")}
onPress={this._onPress_Scan}>
</Button>
</View>
)}
</View>
);
}
}
export default Tickets;
This gives me (after pressing the button) :
SNACK CODE TEST
I notice You are using a component from Expo called BarCodeScanner
There's a github issue open about the fact that this component is not possible to be styled for full screen: https://github.com/expo/expo/issues/5212
However one user proposes a good solution: replace BarCodeScanner with Camera and use barcodescannersettings
Here's a link for the answer on the gitHub issue: https://github.com/expo/expo/issues/5212#issuecomment-653478266
Your code should look something like:
renderBarcodeReader = () => {
const { hasCameraPermission, scanned } = this.state;
[ ... ] // the rest of your code here
return (
<View
style={{
flex: 1,
...StyleSheet.absoluteFillObject
}}
>
<Camera
onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned}
style={{ flex:1}}
barCodeScannerSettings={{
barCodeTypes: [BarCodeScanner.Constants.BarCodeType.qr],
}}
/>
</View>
);
}

What changes should I make to add marker on the map?

This is what I implemented so far. I am unable to add a marker to the current location on the map. Although I am able to get the current location as well as coordinates using the function findCoordinates() But I am unable to display on the map. Please suggest me where I am wrong or what should I do?
Here is the code I am sharing with you. Please suggest me the better ways to do it.
Thanks in advance
export default class App extends React.Component {
state = {
mapRegion: null,
hasLocationPermissions: false,
locationResult: null,
location: null,
};
componentDidMount() {
this.getLocationAsync();
}
handleMapRegionChange = mapRegion => {
this.setState({ mapRegion });
};
async getLocationAsync () {
// permissions returns only for location permissions on iOS and under certain conditions, see Permissions.LOCATION
const { status, permissions } = await Permissions.askAsync(
Permissions.LOCATION
);
if (status === 'granted') {
this.setState({ hasLocationPermissions: true });
// let location = await Location.getCurrentPositionAsync({ enableHighAccuracy: true });
let location = await Location.getCurrentPositionAsync({});
this.setState({ locationResult: JSON.stringify(location) });
// Center the map on the location we just fetched.
this.setState({
mapRegion: {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
latitudeDelta: 0.04,
longitudeDelta: 0.05,
},
});
} else {
alert('Location permission not granted');
}
};
findCoordinates = () => {
navigator.geolocation.getCurrentPosition(
position => {
const location = JSON.stringify(position);
this.setState({ location });
},
error => Alert.alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
};
render() {
return (
<View style={styles.container}>
<MapView
style={styles.mapStyle}
region={this.state.mapRegion}
onRegionChange={this.handleMapRegionChange}
/>
<Ionicons style = {{paddingLeft: 0}} name = "md-locate" size = {30} color = "red"
onPress = {this.findCoordinates}
/>
<TouchableOpacity onPress={this.findCoordinates}>
<Text style={styles.welcome}>My Location</Text>
<Text>Location: {this.state.location}</Text>
</TouchableOpacity>
</View>
);
}
}
App.navigationOptions = {
title: 'Location',
headerStyle: {
backgroundColor: '#ff6666',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
fontSize:20
},
};
import { Marker } from 'react-native-maps';
//you need to set the initial latitude and longitude
value with deltas and use the marker component from react-native-maps
<MapView
style={styles.mapStyle}
region={this.state.mapRegion}
onRegionChange={this.handleMapRegionChange}>
<Marker
coordinate={this.state.location}
title={marker.title}
description={marker.description}
/>
</MapView>
You could try below
findCoordinates = () => {
navigator.geolocation.getCurrentPosition(
position => {
this.setState({ location });
},
error => Alert.alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
};
render() {
return (
<View style={styles.container}>
<MapView
style={styles.mapStyle}
region={this.state.mapRegion}
onRegionChange={this.handleMapRegionChange}
>
{this.state.location && (
<MapView.Marker
coordinate={this.state.location.coords} // <-- Pass coordinate { latitude: number, longitude: number }
/>
)}
</MapView>
</View>
)
}

How can I render my markers inside the ClusteredMapView?

I am trying to render the markers inside the component <ClusteredMapView/> but it do not happen, just render the marker with none markers...
Bellow some code:
render() {
return (
<ClusteredMapView
style={{ flex: 1 }}
data={this.state.data}
initialRegion={INIT_REGION}
ref={r => {
this.map = r;
}}
renderMarkerS={this.renderMarkerS}
renderCluster={this.renderCluster}
/>
);
}
}
here is the renderMarkers function:
renderMarkerS = item =>
this.state.markers.map((marker, index) => {
console.log('Location picker Marker', coords);
const coords = {
location: {
latitude: JSON.parse(item.latitude),
longitude: JSON.parse(item.longitude),
},
};
return (
<Marker
onPress={this.pickLocationHandler}
ref={mark => (marker.mark = mark)}
key={index || Math.random()}
title={'Parada'}
description={marker.hora}
tracksViewChanges={!this.state.initialized}
{...this.props}
pinColor={'tomato'}
coordinate={JSON.parse(item.location)}
//coordinate={coords}
>
{this.props.children}
</Marker>
);
});
With:
componentDidMount() {
return fetch(
'https://gist.githubusercontent.com/MatheusCbrl/bba7db1c0dbc68be2f26d5c7e15649b6/raw/0fab4ea3b493dcd15e95f172cd0a251724efbc45/ParadasDiurno.json'
)
.then(response => response.json())
.then(responseJson => {
// just setState here e.g.
this.setState({
data: responseJson,
isLoading: false,
});
})
.catch(error => {
console.error(error);
});
}
My data is:
[
{
"id": "1",
"location": {
"latitude": "-29.2433828",
"longitude": "-51.199249"
},
"hora": "03:55:00 PM"
},
Some one can help me?
Here is the intere code to your view: https://snack.expo.io/#matheus_cbrl/clusters
I got the follow error:
Device: (3:18096) No cluster with the specified id.
Device: (3:5314) TypeError: t.props.renderMarker is not a function. (In 't.props.renderMarker(e.properties.item)', 't.props.renderMarker' is undefined)
This error is located at:
in e
in MyClusteredMapView
in RCTView
in RCTView
in n
in n
in v
in RCTView
in RCTView
in c
Device: TypeError: t.props.renderMarker is not a function. (In 't.props.renderMarker(e.properties.item)', 't.props.renderMarker' is undefined)
Prettier
Editor
Expo
renderMarker is a function that render just 1 marker. Besides, you use this.state.data for markers but you didn't update it. You could try below
componentDidMount() {
return fetch(
'https://gist.githubusercontent.com/MatheusCbrl/bba7db1c0dbc68be2f26d5c7e15649b6/raw/0fab4ea3b493dcd15e95f172cd0a251724efbc45/ParadasDiurno.json'
)
.then(response => response.json())
.then(responseJson => {
// just setState here e.g.
this.setState({
data: responseJson, <-- update here
isLoading: false,
});
})
.catch(error => {
console.error(error);
});
}
renderCluster = (cluster, onPress) => {
const pointCount = cluster.pointCount,
coordinate = cluster.coordinate;
const clusterId = cluster.clusterId;
return (
<Marker key={clusterId} coordinate={coordinate} onPress={onPress}>
<View style={styles.myClusterStyle}>
<Text style={styles.myClusterTextStyle}>
{pointCount}
</Text>
</View>
</Marker>
);
};
renderMarker(marker) {
console.log('Location picker Marker', marker.location);
const coords = {
latitude: parseFloat(marker.location.latitude),
longitude: parseFloat(marker.location.longitude),
}
return (
<Marker
key={marker.id}
title={'Parada'}
description={marker.hora}
pinColor={'tomato'}
coordinate={coords}
/>
);
}
render() {
return (
<View style={{ flex: 1 }}>
<StatusBar hidden />
<ClusteredMapView
style={{ flex: 1 }}
data={this.state.data}
initialRegion={INIT_REGION}
ref={r => this.map = r}
renderMarker={this.renderMarker}
renderCluster={this.renderCluster}
/>
</View>
);
}

Unexpected behaviour using seek in react-native-video

In react-native-video, whenever I click on the (custom) progress bar on a value less than 50% (half of it), the video jumps to start instead of seeking to the right time. When I click above 50%, it goes to 50%. It's not actually 50, more like 55-60 but whatever. This is really weird, was not able to find anything online!
import Video from 'react-native-video';
import ProgressBar from "react-native-progress/Bar";
class Welcome extends React.Component {
player;
constructor(props) {
super(props)
//this.player = React.createRef();
this.state = {
paused: false,
loaded: false,
progress: 0,
duration: 0,
pressed:false,
screenType: 'contain',
};
console.log("--- Screen --- Welcome")
}
componentDidMount = () => {
setTimeout(() => {
this.player.seek(8)
},8000)
}
handleMainButtonTouch = () => {
console.log("inside handleMainButtonTouch")
console.log(this.state.progress)
if (this.state.progress >= 1) {
this.player.seek(0);
}
this.setState(state => {
return {
paused: !state.paused,
};
});
};
handleProgressPress = e => {
const position = e.nativeEvent.locationX;
const progress = parseFloat(position / 250) * this.state.duration;
const isPlaying = !this.state.paused;
this.player.seek(progress);
};
handleProgress = progress => {
this.setState({
progress: parseFloat(progress.currentTime) / parseFloat(this.state.duration),
});
};
handleEnd = () => {
this.setState({
paused: true ,
progress: 0 ,
});
this.player.seek(0);
};
handleLoad = meta => {
this.setState({
loaded: true,
duration: meta.duration,
});
};
handleFullScreen = () => {
if (this.state.screenType == 'contain')
this.setState({ screenType: 'cover' });
else this.setState({ screenType: 'contain' });
};
render() {
return (
<View style={styles.container}>
<View style={this.handleOuterViewStyle()}>
<Video
paused={this.state.paused}
source={{uri: "https://res.cloudinary.com/dy6bbey4u/video/upload/v1565532579/fam/videos/sample.mp4"}}
resizeMode={this.state.screenType}
onLoad={this.handleLoad}
onProgress={this.handleProgress}
onEnd={this.handleEnd}
ref={ref => {
this.player = ref;
}}
/>
{ this.state.loaded &&
<View style={styles.controls}>
<TouchableWithoutFeedback onPress={this.handleMainButtonTouch}>
<Text>Play</Text>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={this.handleProgressPress}>
<View>
<ProgressBar
animated={false}
progress={this.state.progress}
color="#FFF"
borderColor="#FFF"
width={250}
height={20}
/>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={this.handleFullScreen}>
<Text style={styles.fullscreenButton}>Full</Text>
</TouchableWithoutFeedback>
</View>
}
</View>
</View>
)
}
}
export default Welcome
I was also facing the same problem. Whenever i backward the video, it goes forward. The problem is depending on the video format. I was using the Webm format. Now the mp4 format solved the problem.
P.S. Sorry for the late reply.
ffmpeg -i input.mp4 -force_key_frames "expr:gte(t,n_forced*1)" output.mp4
Solved by forcing adding keyframes to the video.
So the solution for me was changing line 640 from android/src/main/java/com/brentvatne/react/ReactVideoView.java
- super.seekTo(msec);
+ mMediaPlayer.seekTo(msec,3);
Original response: https://github.com/react-native-video/react-native-video/issues/2230#issuecomment-892982288