Location access timed out, position unavaiable in react native - javascript

I have geolocation running in my app. In Xiaomi device in which i'm working on works fine. I tried on 2 other devices, and got Location request timed out error. Here's the code i have:
import React, { Component } from 'react'
import { View, AsyncStorage, Dimensions, PermissionsAndroid } from 'react-native';
const { width, height } = Dimensions.get('window')
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO
class App extends Component {
constructor(props) {
super(props)
this.state = {
initialPosition: {
latitude: null,
longitude: null,
latitudeDelta: null,
longitudeDelta: null
}
}
}
requestLocationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Location Permission',
'message': 'This App needs access to your location ' +
'so we can know where you are.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use locations ")
navigator.geolocation.getCurrentPosition((position) => {
let lat = parseFloat(position.coords.latitude)
let long = parseFloat(position.coords.longitude)
let initialRegion = {
latitude: lat,
longitude: long,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA
}
this.setState({ initialPosition: initialRegion })
this.setState({ markerPosition: initialRegion })
},
(error) => alert(JSON.stringify(error)),
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 }
)
} else {
console.log("Location permission denied")
}
} catch (err) {
console.warn(err)
}
}
componentDidMount() {
this.requestLocationPermission()
}
}
export default App
Some additional information:
React Native version: 0.57.8
Platform: Android
Dev tools: Android SDK v27
i have tried switching enableHighAccuracy to false but that didn't help. The error i get is like this:

Related

React.js geo position not working in browser on iPhone/Android

I'm trying to get my position on a map and it works fine on my computer in Google Chrome, but when simulating to android/iPhone nothing happens when using for example Custom Location on iPhone Simulator. Tried it on my actual iPhone as well without any luck.
All settings I can find for accepting location on simulator/real device is ON
GoogleMap.js
import React from 'react'
import GoogleMapReact from 'google-map-react'
import {usePosition} from "./usePosition";
const defaultProps = {
center: {
lat: 10.0000000,
lng: 12.0000000,
},
zoom: 18.7,
}
const MeOnMap = ({ text }) => <div className="me-on-map"><img src="static/walking.gif" width="30" /></div>
const GoogleMap = () => {
const { latitude, longitude} = usePosition();
return (
<div style={{ marginLeft: '-17px', height: '528px', width: '109%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: '*********' }}
defaultCenter={defaultProps.center}
defaultZoom={defaultProps.zoom}
yesIWantToUseGoogleMapApiInternals
options={{ scrollwheel: false, zoomControl: false, fullscreenControl: false, gestureHandling: 'none', styles: [{ stylers: [{ 'saturation': 100 }, { 'gamma': 0.5 }]}] }}
>
<MeOnMap
lat={latitude}
lng={longitude}
text={''}
/>
</GoogleMapReact>
</div>
)}
export default GoogleMap
geo.js
import React from 'react';
import {usePosition} from './usePosition';
export const UsePositions = () => {
const {latitude, longitude} = usePosition();
return (
<code>
My position,<br/>
latitude: {latitude}<br/>
longitude: {longitude}<br/>
</code>
);
};
usePosition.js
import {useState, useEffect} from 'react';
const defaultSettings = {
enableHighAccuracy: false,
timeout: Infinity,
maximumAge: 0,
};
export const usePosition = (watch = false, settings = defaultSettings) => {
const [position, setPosition] = useState({});
const [error, setError] = useState(null);
const onChange = ({coords, timestamp}) => {
setPosition({
latitude: coords.latitude,
longitude: coords.longitude,
accuracy: coords.accuracy,
speed: coords.speed,
timestamp,
});
};
const onError = (error) => {
setError(error.message);
};
useEffect(() => {
if (!navigator || !navigator.geolocation) {
setError('Geolocation is not supported');
return;
}
let watcher = null;
if (watch) {
watcher =
navigator.geolocation.watchPosition(onChange, onError, settings);
} else {
navigator.geolocation.getCurrentPosition(onChange, onError, settings);
}
return () => watcher && navigator.geolocation.clearWatch(watcher);
}, [
settings.enableHighAccuracy,
settings.timeout,
settings.maximumAge,
]);
return {...position, error};
};
Anyone's got any idea what could be wrong?
Thanks!!
Never mind, it had to do with location being blocked if not gathered from secure connection
Origin does not have permission to use Geolocation service -- even over HTTPS
solved it by running npm with --https

React Native Maps (Mapview Marker) not working

Following is my code segment. Please refer to MapView.Marker, even on giving the coordinates for my current location nothing is displayed, same behavior is observed when i map service locations array and provide latitude,longitude values using it.
When i use mapview marker like this , a single marker is displayed but as for this component i have to display multiple markers on the map with different coordinates i have to go with Mapview.Marker. Please point out what am i missing here.
export default class index extends Component {
constructor(props) {
super(props);
this.state = {
text: "",
source: require("../../Image/User_default.png"),
location: {
latitude: 0,
latitudeDelta: 0,
longitude: 0,
longitudeDelta: 0,
},
serviceLocations: [],
};
}
componentDidMount() {
this._getLocationAsync();
this._getServices();
}
_getServices = () => {
create_service
.getAllServices()
.then((res) => {
this.setState({
serviceLocations: res,
});
})
.catch((error) => {
console.log(error);
});
};
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== "granted") {
Alert.alert("Error", "Permission to access location was denied", [
{ text: "OK" },
]);
} else {
let location = await Location.getCurrentPositionAsync({});
location_service
.setCurrentUserLocation(location)
.then(async (res) => {
// console.log("_getLocationAsync:", res);
})
.catch((err) => console.log(err));
}
};
render() {
const { serviceLocations } = this.state;
return (
<View style={style.container}>
<MapView
style={style.mapStyle}
provider={PROVIDER_GOOGLE}
region={{
latitude: 33.650073,
longitude: 73.153164,
latitudeDelta: 0.0921,
longitudeDelta: 0.0421,
}}
showsUserLocation={true}
/>
<Marker/>
{serviceLocations.length
? serviceLocations.map((serviceLocation,key) => {
return (
<MapView.Marker
coordinate={{
latitude: 33.650073,
longitude: 73.153164,
}}
key={key}
// image={require("../../Image/location-pin.png")}
/>
);
})
: null}
</View>
);
}
}
Sorted the solution myself. Actually what i was doing wrong in this code was that i was using the <Marker> outside the scope of <MapView> which is why markers were not displayed on my maps.
As soon as i corrected the scope issue my problem was solved.

Live Location Tracking in React Native with Expo

Thanks in-advance. I am very new to React.
I'm trying to build an android application with React Native (Expo), PHP and MySQL, which requires live location tracking of salesmen for Admin to monitor.
Can any one please suggest me any idea on Live Location Tracking, even when the salesman's mobile screen is off/screen is locked with application running in background.
Salesman don't need any map component as they have nothing to do with their location. Just a Background Task sending their location details for the Admin, where he can track all his salesman's movement (for whole day) on their field job.
Only one application for both(Admin & Salesman), with dynamic menu based on user type which hides menu items for salesman login.
What is the standard method/process for this job ?
Is their any tutorial which i can follow ?
Any extra suggestions/points which i might be missing.
I have searched the whole internet for few days and i am having difficulty understanding the Expo documentation with very less example. Didn't found any suitable solution.
I just found a solution for my problem, sharing it for anybody who is stuck with the same problem.
Get Users Live Location (every step he takes) with React Native.
Thanks
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import MapView from "react-native-maps";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";
import * as TaskManager from "expo-task-manager";
const LOCATION_TASK_NAME = "background-location-task";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
region: null,
error: '',
};
}
_getLocationAsync = async () => {
await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
enableHighAccuracy: true,
distanceInterval: 1,
timeInterval: 5000
});
// watchPositionAsync Return Lat & Long on Position Change
this.location = await Location.watchPositionAsync(
{
enableHighAccuracy: true,
distanceInterval: 1,
timeInterval: 10000
},
newLocation => {
let { coords } = newLocation;
// console.log(coords);
let region = {
latitude: coords.latitude,
longitude: coords.longitude,
latitudeDelta: 0.045,
longitudeDelta: 0.045
};
this.setState({ region: region });
},
error => console.log(error)
);
return this.location;
};
async componentWillMount() {
// Asking for device location permission
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status === "granted") {
this._getLocationAsync();
} else {
this.setState({ error: "Locations services needed" });
}
userId = (await AsyncStorage.getItem("userId")) || "none";
userName = (await AsyncStorage.getItem("userName")) || "none";
}
render() {
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.region}
showsCompass={true}
showsUserLocation={true}
rotateEnabled={true}
ref={map => {
this.map = map;
}}
style={{ flex: 1 }}
/>
</View>
);
}
}
TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
if (error) {
console.log(error);
return;
}
if (data) {
const { locations } = data;
let lat = locations[0].coords.latitude;
let long = locations[0].coords.longitude;
userId = (await AsyncStorage.getItem("userId")) || "none";
// Storing Received Lat & Long to DB by logged In User Id
axios({
method: "POST",
url: "http://000.000.0.000/phpServer/ajax.php",
data: {
action: "saveLocation",
userId: userId,
lat,
long
}
});
// console.log("Received new locations for user = ", userId, locations);
}
});
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
}
});

How to move marker on the google map react js

I want to move multiple markers on the google map when I get the latitude and longitude from MongoDB. I'm always getting updated latitude and longitude from db, but my markers are not moving, and after refreshing the page, the markers positions are changing, but I need to do it without refreshing the page.
This is my code`
class Maps extends React.Component {
constructor(props){
super(props);
this.state = {
dronePosition: []
};
var _this = this;
const config = {
headers: {
"Authorization" : `Bearer ${localStorage.getItem('token')}`,
}
};
// If I'm using setInterval, the markers are not showing at all. That's why here I call the getAllDrones() function
// setInterval(function(){
axios.get(packages.proxy+'drones/getAllDrones',config)
.then(res => {
//Here I'm always getting updated positions for markers from backend.
_this.state.dronePosition = [];
res.data.forEach( function(element) {
if(element.userId == localStorage.getItem("user_id")){
_this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"})
}
else{
_this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"})
}
});
_this.getAllDrones();
})
// }, 2000)
}
getAllDrones(){
var _this = this;
const config = {
headers: {
"Authorization" : `Bearer ${localStorage.getItem('token')}`,
}
};
axios.get(packages.proxy+'drones/getAllDrones',config)
.then(res => {
_this.state.dronePosition = [];
res.data.forEach( function(element) {
if(element.userId == localStorage.getItem("user_id")){
_this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"})
}
else{
_this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"})
}
});
_this.getAllDrones2();
})
}
getAllDrones2(){
var _this = this;
const config = {
headers: {
"Authorization" : `Bearer ${localStorage.getItem('token')}`,
}
};
axios.get(packages.proxy+'drones/getAllDrones',config)
.then(res => {
_this.state.dronePosition = [];
res.data.forEach( function(element) {
if(element.userId == localStorage.getItem("user_id")){
_this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"})
}
else{
_this.state.dronePosition.push({id: element._id, latitude: element.latitude, longitude: element.longitude, photo: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"})
}
});
_this.getAllDrones();
})
}
render(){
var _this = this;
const { google } = this.props;
const icon = {
url: `data:image/jpeg;base64,${binary_data}`,
scaledSize: new google.maps.Size(40, 40),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(0, 0)
};
return (
<div>
<Header />
<Map className="map" google={google} initialCenter={userLocation} zoom={15} onClick={this.onMapClicked} >
{_this.state.dronePosition.map(marker => (
<Marker
onClick={_this.MarkerClick.bind(_this, marker.id)}
icon={marker.photo}
position={{ lat: marker.latitude, lng: marker.longitude }}
key={marker.id}
/>
))}
</Map>
</div>
)
}
If you want the markers to update without a refresh of the page you need to add them to the component state. Since I don't have access to your mongo-db I've used a dummy api just for demo purpose.
And when making api-calls they should be used in Lifecycle-method componentDidMount, not in the constructor.
I've left out the if-statement for local storage and element.userID since I don't know what that is and the component since I don't have access to it.
import React from "react";
import axios from "axios";
export default class Maps extends React.Component {
constructor(props) {
super(props);
this.state = {
dronePosition: []
};
}
componentDidMount() {
this.refreshMarkers();
}
refreshMarkers = () => {
// Clear state to prevent duplicates
this.setState({dronePosition: []});
const config = {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`
}
};
axios.get("https://swapi.co/api/starships").then(res => {
res.data.results.forEach(element => {
this.setState({
dronePosition: [...this.state.dronePosition, element]
});
});
console.log(this.state.dronePosition);
});
};
render() {
return(
<div>
<div onClick={this.refreshMarkers}>Click on me to refresh markers</div>
render the map here...
</div>
);
}
}

Re-render Header with different icon - React Native

I need help, I have a component, and your function is render de header of app, with right and left icon, and in center is title of current page.
But, I can re-render the title of page, but the icon not re-render.
I not have idea for the solution this.
MyCode of Header.
import React, { Component } from 'react';
import ReactNative from 'react-native';
import { Icon, Text } from './../labsoft.ui';
import styles from './styles';
const Header = ReactNative.StyleSheet.flatten(styles.header);
const BoxHeaderFlex = ReactNative.StyleSheet.flatten(styles.boxHeaderFlex);
const BoxHeaderIcon = ReactNative.StyleSheet.flatten(styles.boxHeaderIcon);
const BoxHeaderTouchable = ReactNative.StyleSheet.flatten(styles.BoxHeaderTouchable);
const BoxHeaderTouchableCenter = ReactNative.StyleSheet.flatten(styles.BoxHeaderTouchableCenter);
interface HeaderProperties {
leftAction?: HeaderLeftAction,
rightAction?: HeaderRightAction,
title?: string;
style?: Style;
}
interface HeaderState {
leftAction?: HeaderLeftAction,
rightAction?: HeaderRightAction,
title?: string;
}
interface HeaderLeftAction {
icon: string;
onClick?: () => void
}
interface HeaderRightAction {
icon: string;
onClick?: () => void
}
interface Style { }
export default class HeaderComponent extends Component<HeaderProperties, HeaderState> {
constructor(props: HeaderProperties) {
super(props);
this.state = {
leftAction: this.props.leftAction,
rightAction: this.props.rightAction,
title: this.props.title
}
}
public setLeftAction(action: HeaderLeftAction) {
this.setState({
leftAction: action
});
}
public setRightAction(action: HeaderRightAction) {
this.setState({
rightAction: action
});
}
public setTitle(title: string) {
this.setState({
title: title
});
}
render() {
console.log('props: ', this.props.rightAction.icon);
console.log('state: ', this.state.rightAction.icon);
let iconRight = this.state.rightAction.icon;
let iconLeft = this.state.leftAction.icon;
return (
<ReactNative.View style={[BoxHeaderFlex, { ...this.props.style }]}>
{
this.state.leftAction != null ?
<Icon icon={iconLeft} onPress={this.state.leftAction.onClick} />
:
<ReactNative.TouchableOpacity style={BoxHeaderTouchable}>
<ReactNative.View>
</ReactNative.View>
</ReactNative.TouchableOpacity>
}
{
this.state.title != null ?
<Text style={BoxHeaderTouchableCenter}>{this.state.title}</Text>
:
<Text style={BoxHeaderTouchableCenter} />
}
{
this.state.rightAction != null ?
<Icon icon={iconRight} onPress={this.state.rightAction.onClick} />
:
<ReactNative.TouchableOpacity style={BoxHeaderTouchable}>
<ReactNative.View>
</ReactNative.View>
</ReactNative.TouchableOpacity>
}
</ReactNative.View >
);
}
}
My request for the change icon in other page (example: geolocation)
import React, { Component } from 'react';
import ReactNative from 'react-native';
import { styles, Container, Text } from './labsoft/labsoft.ui';
import App from "./app";
import { BasicPageProperties, BasicPageState, BasicPage } from './interfaces/generics/basicPage';
export interface GeolocationPageProperties extends BasicPageProperties {
}
export interface GeolocationPageState {
latitude: any,
longitude: any,
address: any,
error: any
}
export default class GeolocationPage extends BasicPage<GeolocationPageProperties, GeolocationPageState> {
constructor(props: GeolocationPageProperties) {
super(props);
this.state = {
latitude: null,
longitude: null,
address: null,
error: null,
};
}
componentWillMount() {
this.app.header.setRightAction({
icon: 'star',
onClick: () => { }
})
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
address: "",
error: null,
});
console.log('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&sensor=true');
// fetch('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&sensor=true')
// .then((response) => response.json())
// .then((data) => {
// this.setState({
// latitude: position.coords.latitude,
// longitude: position.coords.longitude,
// address: data.results[0].formatted_address,
// error: null,
// });
// })
// .catch((error) => {
// console.error(error);
// });
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 10000, maximumAge: 1000 },
);
}
render() {
return (
<Container>
<Text>Latitude: {this.state.latitude}</Text>
<Text>Longitude: {this.state.longitude}</Text>
<Text>Endereço: {this.state.address}</Text>
{this.state.error ? <Text>Error: {this.state.error}</Text> : null}
</Container>
);
}
}
And other code, for request change icon, but not working
import React, { Component } from 'react';
import ReactNative from 'react-native';
import { Container, Text, Button } from './labsoft/labsoft.ui';
import App from "./app";
import { BasicPageProperties, BasicPageState, BasicPage } from './interfaces/generics/basicPage';
export interface MainProperties extends BasicPageProperties {
}
export interface MainState extends BasicPageState {
}
export default class MainPage extends BasicPage<MainProperties, MainState> {
constructor(props: MainProperties) {
super(props);
}
render() {
return (
<Container>
<Button title="aaa" onPress={() => this.app.openDrawer()} />
<Button title="change right action"
onPress={() => {
this.app.header.setRightAction({
icon: "bars",
onClick: () => {
alert("star");
}
})
}} />
</Container>
);
}
}
When navigator render other page, i set null in header icon.
it's working

Categories

Resources