Geolocation error in android - android

here is the code below
if (navigator.geolocation) {
alert("ok");
// var options = { timeout: 0, maximumAge: 600000 };
navigator.geolocation.watchPosition(onSuccess, onError);
}
function onSuccess(position) {
alert("success");
lat = position.coords.latitude;
lng = position.coords.longitude;
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
It works in all browsers , iphone and WindowsPhone. But in andorid in gives me error code :3 timeout expired error.
I enabled gps, wi-fi also in the settings menu--> location services -->location and Google Search,
In the browser menu settings--> privacy and settings enable location is checked.
What is the problem , any ideas? i really stuck in.

Normally , we accept the website request that wants to share your location.
In android if you do not see the question then in the browser settings advanced--> website settings add your URL to there.
It solves the problem.

Related

Why doesn't the cordova-plugin-background-mode plugin work on android?

I'm trying to send the geolocation by ajax in intervals of 30 seconds in the background, since this application is being used to know the "real time" location of the deliverers at all times. The problem is that when you enable the plugin in the android version when generating the apk and installing it on the cell phone it doesn't work, even when you put the application in the background and put it back in the foreground it restarts completely.
These are the versions that I am using for the development of the application:
Cordova 10
Nodejs 14.16
JQuery 3.5
Structure:
js
login.js
home.js
index.html -- this is the login page where the login.js file is located
home.html -- this is the home page where the home.js file is located
login.js
document.addEventListener('deviceready', function () {
cordova.plugins.backgroundMode.enable();
});
home.js
let isSending = false;
let intervalId = null;
let email = window.localStorage.getItem("user_email");
let token = window.localStorage.getItem("token");
let path = window.localStorage.getItem("api_url");
let onMapSuccess = function (position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
if (!isSending) {
$.ajax({
type: "GET",
url: path + "/geoTransportista/" + email + "/" + latitude + "/" + longitude,
headers: {
Authorization: "Bearer " + token,
"Content-type": "application/json",
},
beforeSend: function() {
isSending = true;
}
}).done((res) => {
if (res.state == "successful") console.log("ENVIO EXITOSO");
}).fail((err) => {
console.log(err);
}).always(() => {
isSending = false;
});
}
};
let onMapError = function (error) {
isSending = false;
}
let getLocation = () => {
navigator.geolocation.getCurrentPosition(onMapSuccess, onMapError, {
enableHighAccuracy: true,
});
return getLocation;
}
document.addEventListener('deviceready', function (e) {
intervalId = setInterval(getLocation(), 30000);
cordova.plugins.backgroundMode.on('activate', function (e) {
cordova.plugins.backgroundMode.disableWebViewOptimizations();
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(getLocation(), 30000);
});
cordova.plugins.backgroundMode.on('deactivate', function (e) {
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(getLocation(), 30000);
});
});
#justin is wrong it works on Cordova 10+ but it does not support GPS however you can recall GPS function when you resume to app. I'm on Cordova 11.0.0 and its working fine. Also you can take a look a cordova-plugin-advanced-background-mode
cordova-plugin-background-mode does not work on Cordova 10. You can try downgrade to Cordova 9. The repo seems inactive for a while now, not sure if the author will ever fix it.

Ionic 2 / Ionic 3 : How to get current location of a device

None of the answers on stackoverflow worked for me. A lot of them are for Ionic 1 or those answers are deprecated or they are not working for android device.
I have seen a lot of solutions on stackoverflow about getting current location of device but non of them seems to be working for Android .
what i have tried:-
using geolocation.getCurrentPosition() , which is working for IOS and browser but not for Android.
using this.geolocation.watchPosition() , which is working for IOS and browser but not for Android.
using navigator.geolocation.getCurrentPosition(),which is working for IOS and browser but not for Android.
using fiddle solution provided by this question getCurrentPosition() and watchPosition() are deprecated on insecure origins
Anyway , all of these are deprecated by google due to :-
getCurrentPosition() and watchPosition() are deprecated on insecure
origins, and support will be removed in the future. You should
consider switching your application to a secure origin, such as HTTPS.
See goo.gl/rStTGz for more details.
what worked for me is (https://ionicframework.com/docs/native/background-geolocation/ ) & (https://www.joshmorony.com/adding-background-geolocation-to-an-ionic-2-application/ ) both of these are based on background-geolocation plugin but,it's taking almost 50-55 sec on Android device, again it's working fine for ios
The problem with joshmorony(https://www.joshmorony.com/adding-background-geolocation-to-an-ionic-2-application/ ) solution is foreground is not working for Android physical devices but working fine for browser and ios. Background tracking is working fine , which is taking almost 50 sec to give lat & lng for the first time.
Please help me with this. I want a way to get current location in minimum time. For your info, I am using google javascript map sdk / api .
I tried every solution provided by all of you and others also on internet. Finally i found a solution.You can try this plugin cordova-plugin-advanced-geolocation (https://github.com/Esri/cordova-plugin-advanced-geolocation ) from ESRI . But this plugin will work for Android not IOS. For ios you can go with same old approach . i.e - using this.geolocation.getCurrentPosition(...) or this.geolocation.watchPosition(..).
Add cordova-plugin-advanced-geolocation Plugin Like this :-
cordova plugin add https://github.com/esri/cordova-plugin-advanced-geolocation.git
then Add below line at the top of Class / Component
declare var AdvancedGeolocation:any; //at the top of class
Now add these lines inside relevant function of component ( P.S. - I have included code for both Android & IOS)
//**For Android**
if (this.platform.is('android')) {
this.platform.ready().then(() => {
AdvancedGeolocation.start((success) => {
//loading.dismiss();
// this.refreshCurrentUserLocation();
try {
var jsonObject = JSON.parse(success);
console.log("Provider " + JSON.stringify(jsonObject));
switch (jsonObject.provider) {
case "gps":
console.log("setting gps ====<<>>" + jsonObject.latitude);
this.currentLat = jsonObject.latitude;
this.currentLng = jsonObject.longitude;
break;
case "network":
console.log("setting network ====<<>>" + jsonObject.latitude);
this.currentLat = jsonObject.latitude;
this.currentLng = jsonObject.longitude;
break;
case "satellite":
//TODO
break;
case "cell_info":
//TODO
break;
case "cell_location":
//TODO
break;
case "signal_strength":
//TODO
break;
}
}
catch (exc) {
console.log("Invalid JSON: " + exc);
}
},
function (error) {
console.log("ERROR! " + JSON.stringify(error));
},
{
"minTime": 500, // Min time interval between updates (ms)
"minDistance": 1, // Min distance between updates (meters)
"noWarn": true, // Native location provider warnings
"providers": "all", // Return GPS, NETWORK and CELL locations
"useCache": true, // Return GPS and NETWORK cached locations
"satelliteData": false, // Return of GPS satellite info
"buffer": false, // Buffer location data
"bufferSize": 0, // Max elements in buffer
"signalStrength": false // Return cell signal strength data
});
});
} else {
// **For IOS**
let options = {
frequency: 1000,
enableHighAccuracy: false
};
this.watch = this.geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => {
// loading.dismiss();
console.log("current location at login" + JSON.stringify(position));
// Run update inside of Angular's zone
this.zone.run(() => {
this.currentLat = position.coords.latitude;
this.currentLng = position.coords.longitude;
});
});
}
EDIT : First installation is always going fine. But Sometimes you might get errors for no reason in subsequent installations. To make this error (any error with this plugin ) go away.Follow these steps :
1. Remove this plugin from your project (including config.xml and package.json).
2. Delete/Remove android platform.
3. Delete plugins folder.
4. Now reinstall this plugin again, following the steps above.
I have gone through the problem and find the solution.
the best way to get geolocation of the user is to use this plugin https://ionicframework.com/docs/native/geolocation/
do not forget to add this is app.moudle.ts as its a provider.
by simply adding this code in app component i was able to get location( do not forget to import and add in constructor)
this.geolocation.getCurrentPosition({ enableHighAccuracy: true }).then((resp) => {
console.log(resp);
}, Error => {
console.log(Error);
}).catch(Error => {
console.log(Error);
})
i only have the same error while i was using ionic cordova run
android --livereload that is insecure origin
but when i use ionic serve i can see the response in browser and also after
using ionic cordova run android
just to confirm response in android i check the chrome debugger.
It works for me
import { Geolocation } from '#ionic-native/geolocation/ngx';
import { NativeGeocoder, NativeGeocoderOptions, NativeGeocoderResult } from '#ionic-native/native-geocoder/ngx';
geoencoderOptions: NativeGeocoderOptions = {
useLocale: true,
maxResults: 5
};
constructor(
private geolocation: Geolocation,
private nativeGeocoder: NativeGeocoder
) {
getCurrentLocation() {
this.geolocation.getCurrentPosition()
.then((resp) => {
this.getGeoencoder(resp.coords.latitude, resp.coords.longitude);
}).catch((error) => {
console.log('Error getting location', error);
});
}
//geocoder method to fetch address from coordinates passed as arguments
getGeoencoder(latitude, longitude) {
this.nativeGeocoder.reverseGeocode(latitude, longitude, this.geoencoderOptions)
.then((result: NativeGeocoderResult[]) => {
const address = this.generateAddress(result[0]);
})
.catch((error: any) => {
// alert('Error getting location' + JSON.stringify(error));
});
}
//Return Comma saperated address
generateAddress(addressObj) {
let obj = [];
let address = "";
for (let key in addressObj) {
obj.push(addressObj[key]);
}
obj.reverse();
for (let val in obj) {
if (obj[val].length)
address += obj[val] + ', ';
}
return address.slice(0, -2);
}
you need to provide the permission for Android app as follows:
<feature name="Geolocation">
<param name="android-package" value="org.apache.cordova.GeoBroker" />
</feature>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
I ran into a similar problem. When I build from the terminal with the --prod flag, I no longer see this error since it is now requesting position over https.
Built without --prod flag
Built using the --prod flag
Edit: Sorry for the format, I hope that this makes a little more sense. I used the following function in a service that I could call from anywhere to get the latitude, longitude, accuracy, and timestamp. The key though is using the --prod flag in the terminal when building the app.
this.geolocation.getCurrentPosition().then(position => {
let locationObj = {
lat: position.coords.latitude,
lon: position.coords.longitude,
timestamp: position.timestamp,
accuracy: position.coords.accuracy
};
resolve(locationObj);
})
this method is working for bot android and browser
watchLocation() {
this.watchLocationUpdates = this.geolocation.watchPosition({ maximumAge: 60000, timeout: 25000, enableHighAccuracy: true })
.subscribe(resp => {
this.latitude = resp.coords.latitude;
this.longitude = resp.coords.longitude;
this.altitude = resp.coords.altitude;
this.accuracy = resp.coords.accuracy;
this.altAccuracy = resp.coords.altitudeAccuracy;
this.heading = resp.coords.heading;
this.speed = resp.coords.speed;
this.timestamp = new Date(resp.timestamp);
});
}
I found solution for me: use google api https://www.googleapis.com/geolocation/v1/geolocate?key={API_KEY}
If platform Android I use google api.

How can I retrieve the latitude and longitude using Ionic?

How can I get the latitude/longitude using the Ionic Framework. In Android it sometimes provides it as intended and sometimes it doesn't give latitude/longitude using the following:
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
You could use a call to a URL API which returns a JSON object, and then get the latitude and longitude. The following example calls http://freegeoip.net/json/ and prints out the results. To access the latitude and longitude, you would use the result.latitude and result.longitude fields.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://freegeoip.net/json/", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
this is an example how to get Lat,Long using https://github.com/apache/cordova-plugin-geolocation
.controller('MyCtrl', function($scope, $cordovaGeolocation) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + ' ' + long)
}, function(err) {
console.log(err)
});
var watchOptions = {timeout : 3000, enableHighAccuracy: false};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
console.log(err)
},
function(position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + '' + long)
}
);
watch.clearWatch();
})
You also noticed posOptions and watchOptions objects. We are using timeout to adjust maximum length of time that is allowed to pass in milliseconds and enableHighAccuracy is set to false. It can be set to true to get the best possible results but sometimes it can lead to some errors. There is also maximumAge option that can be used to show how old position is accepted. It is using milliseconds, the same as timeout option.
When we start our app and open the console it will log the latitude and longitude of the device. When our position is changed, the lat and long values will change.
Not quite sure what you are asking here, but Ionic can't give you geolocations, cordova however can. If you want to make it easy for yourself you should look into ngCordova, it's a angular wrapper for cordova plugins. Have a look here: http://ngcordova.com/docs/plugins/geolocation/

phonegap: how to check if gps is enabled

I want to show an alert saying that "Please turn on your GPS".
How can I get GPS status using phonegap?
I have used following code but I don't get any alert message if GPS is turned off. Instead nothing happens.
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var test= navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + position.timestamp + '<br />';
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body>
<p id="geolocation"> Finding geolocation...</p>
</body>
</html>
Assuming we're talking just about Android platform only, as #Joerg rightly says, you can use cordova.plugins.diagnostic to check if GPS is enabled using isGpsLocationEnabled():
cordova.plugins.diagnostic.isGpsLocationEnabled(function(enabled){
console.log("GPS location is " + (enabled ? "enabled" : "disabled"));
}, function(error){
console.error("The following error occurred: "+error);
});
If the result is that GPS is switched off, you can either switch the user to the location settings page to manually enable GPS:
cordova.plugins.diagnostic.switchToLocationSettings();
Or, in addition, you could use cordova-plugin-request-location-accuracy to request high accuracy location mode (i.e. GPS) directly from within the app. This will show a native confirm dialog and if user agrees, GPS will be enabled automatically:
function onRequestSuccess(success){
console.log("Successfully requested accuracy: "+success.message);
}
function onRequestFailure(error){
console.error("Accuracy request failed: error code="+error.code+"; error message="+error.message);
if(error.code !== cordova.plugins.locationAccuracy.ERROR_USER_DISAGREED){
if(window.confirm("Failed to automatically set Location Mode to 'High Accuracy'. Would you like to switch to the Location Settings page and do this manually?")){
cordova.plugins.diagnostic.switchToLocationSettings();
}
}
}
cordova.plugins.locationAccuracy.request(onRequestSuccess, onRequestFailure, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
The answer to your question is below.
You cannot check *if gps is enabled*
You can set a timeout and get the timeout.
You can do this by setting the timeout parameter in the geolocationoptions parameter. (which you did not use)
From the documentation
timeout: The maximum length of time (milliseconds) that is allowed to pass from the call to navigator.geolocation.getCurrentPosition or geolocation.watchPosition until the corresponding geolocationSuccess callback executes. If the geolocationSuccess callback is not invoked within this time, the geolocationError callback is passed a PositionError.TIMEOUT error code. (Note that when used in conjunction with geolocation.watchPosition, the geolocationError callback could be called on an interval every timeout milliseconds!) (Number)
WAIT I WAS WRONG
There is now a plugin that checks to see if the GPS is turned on.
In fact, more than one.
https://www.npmjs.com/package/cordova-plugin-fastrde-checkgps
https://www.npmjs.com/package/cordova-plugin-android-gpsdetect
The best way to check if GPS, Wifi, … is enabled, is to use this plugin:
https://www.npmjs.com/package/cordova.plugins.diagnostic
Using this plugin you can check a lot of features and you can switch the user to the settings.

How to stop watchPosition() Position retrieval timed out error?

I am developing a phonegap application that uses the current location of the device in its functionalities but when tested on Iphone the App give an error message every 60 seconds as follows:
The Source code I am using to get the location is:
function onDeviceReady() {
var options = { maximumAge: 0, timeout: 10000,enableHighAccuracy: false };
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
function onSuccess(position) {
if (position.coords.latitude) {
sessionStorage.setItem("appLatitude", position.coords.latitude);
sessionStorage.setItem("appLongitude", position.coords.longitude);
}
//alert(sessionStorage.getItem("appLatitude") + "&" + sessionStorage.getItem("appLongitude"));
}
function onError(error) {
z.appNotification.getAlert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
How can stop that error message from prompting?
If you only want to get the location once use:
navigator.geolocation.getCurrentPosition(onSuccess, onError);
If you want to stop watching for any reason, use:
navigator.geolocation.clearWatch(watchID);

Categories

Resources