I'm using Geolocation in React-Native to receive my current location to load object around me. Below is my code.
getCurrentPosition() {
console.log("checkLocation", "getCurrentPosition1");
navigator.geolocation.getCurrentPosition(
position => {
const { coords } = position;
if (coords !== undefined) {
console.log("checkLocation", "getCurrentPosition trigger");
this.setState({
currentCoordinate: coords,
prevCoorForGet: coords,
prevCoorForUpdate: coords
});
this.props.saveCurrentLocation({
currentLocation: {
latitude: coords.latitude,
longitude: coords.longitude
}
});
this.loadContent(coords);
}
},
error =>
console.log(
"checkLocation",
"getCurrentPosition " + JSON.stringify(error)
),
{
enableHighAccuracy: true,
timeout: 60000,
maximumAge: 3600000
}
);
}
The problem is this code working fine in the first time. But when I navigate to another scene and go back, It isn't work anymore and give me a time out error. Sometime it works, sometime it doesn't. Please help me fix it.
This one is working fine (both ios and android) in my project even working after navigating between pages and return map screen.
navigator.geolocation.getCurrentPosition(
(position) => {
// user location's latitude and longitude
let latitude = parseFloat(position.coords.latitude);
let longitude = parseFloat(position.coords.longitude);
console.log('location position: ', position);
let region = {
latitude: latitude,
longitude: longitude,
latitudeDelta: 0.0522,
longitudeDelta: 0.0321,
};
// to store region data
this.setState({region: region});
//animate to user current location
this.map.animateToRegion(region,1000)
},
(error) => console.log('position error!!!', error),
{enableHighAccuracy: false, timeout: 3000}
);
I hope it works on your project too
Edit
If still not working
/**
* when return the page this listener will trigger
*/
this.props.navigation.addListener('willFocus', (payload) => {
// call location method again
this.getLocation()
});
Try below code, this seems to work for me
import Geolocation from 'react-native-geolocation-service';
componentWillUnmount() {
Geolocation.stopObserving();
}
use your function in componentWillMount() so that every time the component mounts....it function will be executed
Related
I am testing background location tasks in react native with Expo's taskmanager to test when I enter a geofence. I've got the basics working but I am now trying to access the values within a promise that is returned from one of the tasks so i can display if you've entered or exited the geofence. Can anyone help me figure out how to properly access the values I want?
Below is the task portion relevant to the geofence. I return the value region which comes as a promise. I haven't been able to figure out how to send directly from task manager yet:
// 3 Define geofencing task
TaskManager.defineTask(TASK_CHECK_GEOFENCE, ({ data: { eventType, region }, error }) => {
if (error) {
// check `error.message` for more details.
return;
}
if (eventType === Location.GeofencingEventType.Enter) {
console.log("You've entered region:", region);
//this.props.setEnterRegion({ inRegion: region })
const final = region
return final
} else if (eventType === Location.GeofencingEventType.Exit) {
console.log("You've left region:", region);
const final = region
return final
}
});
Then within App.js I call the app in componentDidMount:
componentDidMount() {
this.getLocationsPermissions();
this.startBackgroundUpdate();
this.startGeofence();
}
//define and start geofence
startGeofence = async () => {
console.log('starting geofencing test ...')
let x = Location.startGeofencingAsync('TASK_CHECK_GEOFENCE',
[
{
identifier: 'court',
latitude: this.state.myLocation.latitude,
longitude: this.state.myLocation.longitude,
radius: 20,
notifyOnEnter: true,
notifyOnExit: true,
}
]
)
this.sendTask(x)
};
When I try to access the value I can see the promise and I am unsure where I am going wrong. I would perfer to send to the store directly from taskmanager but I am having trouble with that:
//send to store from task
sendTask = (x) => {
console.log('entered region...', x)
this.props.setEnterRegion(x)
entered region... Promise {
"_40": 0,
"_55": null,
"_65": 0,
"_72": null,
}
UPDATED
Found out more information about this question on the github page from the library I use.
Answer:
When using the library react-native-maps-directions the google API only gets triggered when the origin, destination or waypoint updates. Since then there is a new calculation needed.
Question:
So I have this question because I currently am using the Google Directions API which uses the "pay-as-you-go model". Now I am scared to use the API in my code that when the user location updates it will triggers the API again so it will think I want a new result from the Directions API.
I'm using the react-native-maps-directions library to show the route on the map.
There is just more clarification needed for me.
Does the API only get called once when opening the component or will
it also trigger during the update of the user location even I don't
want to do something with the user location in the query?
Here is a part of my code that shows the current flow I'm talking about:
The API Key gets registered in the constructor
constructor(props){
super(props);
if (props.apiKey !== undefined) {
this.apiKey = props.apiKey;
}
this.origin = { latitude: this.route.waypoints[0].latitude, longitude:
this.route.waypoints[0].longitude };
this.destination = { latitude: this.route.waypoints[this.route.waypoints.length - 1].latitude, longitude: this.route.waypoints[this.route.waypoints.length - 1].longitude };
this.GOOGLE_MAPS_APIKEY = this.apiKey;
}
The getUserLocation get called in componentWillUnmount (It is the only thing that has to update and I don't want to make this to trigger the API)
getUserLocation = async () => {
this.location = await Location.watchPositionAsync(
{
enableHighAccuracy: true,
distanceInterval: 1,
timeInterval: 100,
},
(newLocation) => {
let coords = newLocation.coords;
console.log("USER LOCATION", coords);
this.setState({
userLocation: coords,
region: {
LATITUDE: coords.latitude,
LONGITUDE: coords.longitude
}
});
},
(error) => console.log(error)
);
};
I use the API Key in the render, not where the marker of the user get updated
<MapViewDirections
origin={this.origin}
waypoints={this.coordinates.slice(1, -1)}
destination={this.destination}
apikey={this.GOOGLE_MAPS_APIKEY}
strokeWidth={20}
strokeColor="#DD8526"
/>
This is the marker that gets updated, it's in the same MapView as the block above
<Marker style={styles.markerStyle} coordinate={{ latitude: lat, longitude: lng }} title="Your Location">
<Text style={styles.markerTextStyle}>You</Text>
<Image source={require("./../../assets/img/other/you.png")} style={{ height: 20, width: 20 }/>
</Marker>
There is only one Component in the render that updates so I don't know if this will actually trigger the API call again.
Feel free to say it when you need anything to be more specified to bring the right information about this!
I would like to know how I can do to detect if during any moment of the execution of an Ionic 4 app (not only at the beginning of the app), the user manually turns off or on the GPS.
What Ionic 4 event can I hear from the GPS, to be able to alert at any time of the execution of the app if the user turned off or on the GPS?
Thank you very much and sorry for my bad English
My code on app.component.ts:
initializeApp() {
this.platform.ready().then(() => {
this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT_PRIMARY);
this.platform.backButton.subscribeWithPriority(9999, () => {
document.addEventListener('backbutton', function (event) {
event.preventDefault();
event.stopPropagation();
}, false);
this.presentAlertConfirm();
});
this.geolocation.getCurrentPosition().then((resp) => {
this.global.origin = { lat: resp.coords.latitude, lng: resp.coords.longitude };
this.global.latitude = resp.coords.latitude;
this.global.longitude = resp.coords.longitude;
}).catch((error) => {
console.log('Error getting location', error);
});
let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
this.global.origin = { lat: data.coords.latitude, lng: data.coords.longitude };
this.global.latitude = data.coords.latitude;
this.global.longitude = data.coords.longitude;
}, error => {
console.log('Error getting location in WATCH', error); //error handling //
})
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
You have to watch for some GPS change. As proposed in the Ionic 4 documentation and as you have done correctly:
this.watch = this.geolocation.watchPosition();
this.watch.subscribe((data) => {
// usable data
}, (error) => {
// some error
}, { timeout: 30000 });
timeout: The maximum length of time (milliseconds) that is allowed to pass without receiving a set of coordinates.
And remeber to unsubscribe on destroy:
public ngOnDestroy(): void {
this.watch.unsubscribe();
}
I want to stop the location request when the app is in background.
React-Native version 0.53.3
This is my code for starting the watch:
this.setState.watchID = navigator.geolocation.watchPosition((lastPosition) => {
this.setState({ position: { longitude: lastPosition.coords.latitude, latitude: lastPosition.coords.longitude } });
if (typeof this.state.geoQuery != "undefined") {
if (this.state.gpsError == true) {
this.setState({
gpsError: false
})
}
this.state.geoQuery.updateCriteria({
center: [lastPosition.coords.longitude, lastPosition.coords.latitude],
radius: 1500
});
}
},
(error) => this.setState({ gpsError: true }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 0, distanceFilter: 1 });
This is where I want to clear the watch:
componentWillUnmount() {
navigator.geolocation.clearWatch(this.state.watchID);
}
The ID I'm getting is always 0,
I have to force close the APP to stop the location, this translates in lot of battery usage if the user don't force close the APP.
Any ideas? Thanks.
I know this is very late, but I had this problem also in v. 0.66
My problem was that i used useState to set the ID which was then somehow translated into false which is not an ID ofcause..
so the solution was for me to set it back to 0....
if(!ID) {
ID = 0
}
Geolocation.clearWatch(ID)
How can make the app that will be run on the iOS simulator get the geolocation.
Currently I can only get the error output I have written for the error callback for the getCurrentPosition() or the watchPosition().
I have this code in one of my components:
componentDidMount: function(){
var geo = navigator.geolocation;
var positionOptions = {
enableHighAccuracy: true,
timeout: 3000,
maximumAge: 0,
};
var success = function(position){
this.setState({
region: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
},
});
};
var error = function(error){
alert('error watchposition:', error.code);
};
var watchID = geo.watchPosition(success, error, positionOptions);
// geo.getCurrentPosition(success, error, positionOptions);
},
Make sure you have a correct custom location in the debug menu for the simulator.
Also make sure location services enabled in the simulator for your app.