I have a function triggered by button click that checks geolocation..it works fine on phones when geolocation is on, and when off, a message saying so displays, as expected. The problem occurs when first the phone's location service is turned off, the button is clicked(message pops up, as expected), then if the user turns location services back on while app is still open, and again clicks the button, still the same 'no location service' message pops up.
Is there a way to check if the phone's location service is turned on or off on each button click? Getting the same results on Android and IOS.
code:
$(document).ready(function () {
$('#smallScreenGeolocate').on('click', function(){
getCurrentLocation();
});
});
function getCurrentLocation () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(addGeolocationMarker, locationError);
return true;
}
else {
alert("Browser doesn't support Geolocation. Visit http://caniuse.com to discover browser support for the Geolocation API.");
return false;
}
}
Check this answer from another SO post https://stackoverflow.com/a/14862073/6539349
You have to check what was the error as suggested here http://www.w3schools.com/html/html5_geolocation.asp
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
The second parameter showError of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
Related
I need to report the current location of the device using a flutter app. I need to do that continiuesly even when the app is closed.
I currently implemented it using background_fetch which does the job about every 15 minutes.
It works well when the app is open or minimized. But when the app is closed, it functions in Headless mode and doesn't work. the Exception is:
MissingPluginException(No implementation found for method getLocation on channel lyokone/location)
It seems that in Headless mode, not all the app is loaded in memory. I don't have any idea how to solve it.
Also I tried using an Isolate but I face with a new exception:
native function 'Window_sendPlatformMessage' (4 arguments) cannot be found.
Anybody knows how to solve these problems or have any new idea to do the location tracking?
Another option is use package https://github.com/Lyokone/flutterlocation https://github.com/Lyokone/flutterlocation/wiki/Background-Location-Updates
Support To get location updates even your app is closed, https://github.com/Lyokone/flutterlocation/wiki/Background-Location-Updates might have bugs
Also from transistorsoft and provide Android Headless Mod but need license
transistorsoft package https://github.com/transistorsoft/flutter_background_geolocation/wiki/Android-Headless-Mode
Android Headless Mod https://github.com/transistorsoft/flutter_background_geolocation/wiki/Android-Headless-Mode
code snippet
import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;
void headlessTask(bg.HeadlessEvent headlessEvent) async {
print('[BackgroundGeolocation HeadlessTask]: $headlessEvent');
// Implement a 'case' for only those events you're interested in.
switch(headlessEvent.name) {
case bg.Event.TERMINATE:
bg.State state = headlessEvent.event;
print('- State: $state');
break;
case bg.Event.HEARTBEAT:
bg.HeartbeatEvent event = headlessEvent.event;
print('- HeartbeatEvent: $event');
break;
case bg.Event.LOCATION:
bg.Location location = headlessEvent.event;
print('- Location: $location');
break;
case bg.Event.MOTIONCHANGE:
bg.Location location = headlessEvent.event;
print('- Location: $location');
break;
case bg.Event.GEOFENCE:
bg.GeofenceEvent geofenceEvent = headlessEvent.event;
print('- GeofenceEvent: $geofenceEvent');
break;
case bg.Event.GEOFENCESCHANGE:
bg.GeofencesChangeEvent event = headlessEvent.event;
print('- GeofencesChangeEvent: $event');
break;
case bg.Event.SCHEDULE:
bg.State state = headlessEvent.event;
print('- State: $state');
break;
case bg.Event.ACTIVITYCHANGE:
bg.ActivityChangeEvent event = headlessEvent.event;
print('ActivityChangeEvent: $event');
break;
case bg.Event.HTTP:
bg.HttpEvent response = headlessEvent.event;
print('HttpEvent: $response');
break;
case bg.Event.POWERSAVECHANGE:
bool enabled = headlessEvent.event;
print('ProviderChangeEvent: $enabled');
break;
case bg.Event.CONNECTIVITYCHANGE:
bg.ConnectivityChangeEvent event = headlessEvent.event;
print('ConnectivityChangeEvent: $event');
break;
case bg.Event.ENABLEDCHANGE:
bool enabled = headlessEvent.event;
print('EnabledChangeEvent: $enabled');
break;
}
}
void main() {
runApp(HelloWorld());
// Register your headlessTask:
BackgroundGeolocation.registerHeadlessTask(headlessTask);
}
I have built an app which lets the user control their scrolling action using the fingerprint sensor.
It used to work earlier until some weeks back, where I found that method: isGestureDetectionAvailable() always returns 'False' after starting 'accessibility service'
Since I am getting 'isGestureDetectionAvailable()' as always 'False',
my 'registerFingerprintGestureCallback' doesn't work and hence all my functionality of swiping gestures.
Can Someone please help and point out what I am doing wrong.
Here is my code.
protected void onServiceConnected() {
super.onServiceConnected();
FingerprintGestureController gestureController = getFingerprintGestureController();
Log.e(TAG, "Is available: " + gestureController.isGestureDetectionAvailable());
FingerprintGestureController.FingerprintGestureCallback callback = new
FingerprintGestureController.FingerprintGestureCallback() {
public void onGestureDetectionAvailabilityChanged(boolean available) {
super.onGestureDetectionAvailabilityChanged(available);
Log.d(TAG, "onGestureDetectionAvailabilityChanged " + available);
}
public void onGestureDetected(int gesture) {
switch (gesture) {
case FINGERPRINT_GESTURE_SWIPE_UP:
scrollDown();
break;
case FINGERPRINT_GESTURE_SWIPE_DOWN:
scrollUp();
break;
case FINGERPRINT_GESTURE_SWIPE_RIGHT:
execute_swipe_right_functionality();
break;
case FINGERPRINT_GESTURE_SWIPE_LEFT:
execute_swipe_left_functionality();
break;
default:
Log.e("My Service",
"Error: Unknown gesture type detected!");
break;
}
}
};
gestureController.registerFingerprintGestureCallback(callback, new Handler());
}
Can you please help me to check if the location service is enabled or not in Appcelerator.
I am working with Titanium SDk 6.1.2 and Samsung S5 with Marshmellow OS. Even though the GPS is enabled/not in device, But every time it results in false.
Thanks in Advance.
First of all you need to check for Location Permissions for app in Android & then you need to check if location service is enabled in device or not.
Both are different statements.
First one checks for app permission to access location & 2nd is about checking location service is on or off.
Without checking Location Permissions first on Android, you cannot check for location on/off state, else it will always lead to false status.
First of all add this in tiapp.xml in ios -> plist -> dict
<key>NSLocationAlwaysUsageDescription</key>
<string>Determine Current Location</string>
Now here's the cross-compatible code for Android/iOS.
function checkLocationEnabledOrNot(_callback, _args) {
if (Titanium.Geolocation.locationServicesEnabled) {
_callback(_args);
} else {
alert("Turn on location on your device.");
}
}
// pass _callback method you want to call after successful access to location
// you can also pass arguments as 2nd parameter to the function you want to call
function startLocationProcess(_callback, _args) {
Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_HIGH;
if (OS_IOS) {
checkLocationEnabledOrNot(_callback, _args);
} else if (OS_ANDROID) {
if (Ti.Geolocation.hasLocationPermissions()) {
checkLocationEnabledOrNot(_callback, _args);
} else {
Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS, function (locationEvent) {
if (locationEvent.success) {
checkLocationEnabledOrNot(_callback, _args);
} else {
alert("Location permissions are required to access locations.");
}
});
}
}
}
Now, on a button click whatever you want to do after location check, you can simply do it like this:
function anotherFunction(name) {
alert(name);
}
$.someButton.addEventListener('click', function (e) {
startLocationProcess(anotherFunction, "Hello D.Ish");
});
Few days ago, I succeeded in messaging my phone with push plugin. But now, after pushNotification.register is executed, I don't receive a notification that has a registration ID (after pushNotification.register, ecb was not fired). But success handler was fired. One strange thing is success handler is also fired when I turn off every network (Wifi, mobile internet).
So I tried it on another phone (friend's). Then it works well.
What happened in my phone? I searched this issue last few days, but I couldn't find any helpful docs. Is there anybody who has same problem?
var pushNotification;
document.addEventListener("deviceready", function(){
pushNotification=window.plugins.pushNotification;
console.log('Device Ready!!');
register();
});
function register() {
console.log('registering...');
pushNotification.register(
successHandler,
errorHandler,
{
"senderID":"1234567890", // (temporary)
"ecb":"onNotification"
}
);
}
function onNotification(e) {
console.log('======onNotification======');
console.log('type of notification:'+e.event);
switch(e.event) {
case 'registered':
if(e.regid.length>0) {
$("#status").append('<li>regid:'+e.regid+'</li>');
console.log('regid:'+e.regid);
}
break;
case 'message':
if(e.foreground) {
console.log('inline message');
} else {
if(e.coldstart) {
console.log('coldstart message');
} else {
console.log('background message');
}
}
console.log('message:'+e.payload.message);
console.log('msgcnt:'+e.payload.msgcnt);
break;
case 'error':
$("#status").append('<li>error:'+e.msg);
break;
}
}
function successHandler(result) {
console.log('success; result:'+result);
}
function errorHandler(error) {
console.log('error; error:'+error);
}
I am working on an Android 3.2+ app in Titanium. It is crucial that I am able to determine if the device has GPS enabled. According to the Titanium API reference, Ti.Geolocation.locationServicesEnabled will always return true on Android 2.2+, because of a new "passive" location provider. Is there any other way of determining if GPS is truly enabled?
Thanks.
i think this code should work for you:
//check to see if we have GPS capabilities
if(Titanium.Geolocation.isLocationProviderEnabled(Titanium.Geolocation.PROVIDER_GPS, Titanium.Geolocation.ACCURACY_BEST) == false) {
var alertDlg = Titanium.UI.createAlertDialog({
title:'MileTrackGPS',
message:'GPS is OFF. Enable it in Settings.',
buttonNames: ['Cancel', 'Open Settings']
});
alertDlg.cancel = 0;
alertDlg.addEventListener('click', function(e){
if(!e.cancel) {
//open up the settings page
var settingsIntent = Titanium.Android.createIntent({
action: 'android.settings.LOCATION_SOURCE_SETTINGS'
});
activity.startActivity(settingsIntent);
}
else {
//close the window to exit
win.close();
}
});
alertDlg.show();
}
refrence
Alright here is an easy solution I came up with and it works well for me. I have a global variable 'timeStamp' which I initially set to zero.
Titanium.Geolocation.getCurrentPosition(function(e){
//only update fields if timer is still active
if(gpsTimer!=null)
{
//if the provider is not GPS or the timestamp is the same as the last, we do not want the results. We need to alert the user that they need to turn their GPS on.
if(e.provider['name']!="gps" || timeStamp==e.coords.timestamp)
{
//clear timeout
clearTimeout(gpsTimer);
gpsTimer = null;
//close window
get_gps_win.close();
//garbage collection
get_gps_win = null;
gpsLatField = null;
gpsLongField = null;
gpsAccuracyField = null;
timeStamp=0;
//alert user
alert("This feature is not available unless you have GPS turned on. Please turn GPS on and then try again.");
}
else
{
//update fields
gpsLatField.value=ConvertDDToDMSPlain(e.coords.latitude);
gpsLongField.value=ConvertDDToDMSPlain(e.coords.longitude);
gpsAccuracyField.value=e.coords.accuracy+" meters/"+(e.coords.accuracy*3.28084)+" feet";
gpsTimer=setTimeout(function() {
Titanium.Geolocation.fireEvent('location');
}, 1000);
}
timeStamp= e.coords.timestamp;
}
});