I'm using the following to successfully capture user's location (mobile browser):
<script>
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(handlePosition);
}
function handlePosition(pos) {
//this passes lat/long to additional code
}
</script>
This works, but often times the browser will seemingly cache the location data. The page that calls this geolocation code shows information relative to the user's location, so what happens is the user can move (change location), the page is reloaded, but the previous location data is used (showing incorrect data). Sometimes the page will have to be refreshed once or even twice for the page to use new location data.
Does anyone know of any means to force the code to get and use "up to date" location data each time script is executed?
FWIW, I'm experiencing problem in iOS Safari (6.1). Have not been able to test in Android yet.
Thanks for reading and for any help.
Edit: As Oleksiy has written in his answer, the Geolocation API now supports this. You can add {maximumAge: 0} as the third option parameter of getCurrentPosition. There is also a timeout and a high accuracy option available in the PositionOptions as noted in the specification.
Your navigator call would change to the following:
navigator.geolocation.getCurrentPosition(
handlePosition,
(error)=>{},
{maximumAge:0}
);
No can't be done. You don't have any control over the browser geolocation other than the code in your example. The html5 geo location api is very, very limited and that is a pain. I also had a question whether I could ask it if permission for the domain had already been granted and the answer was also no.
The problem is that the api is implemented in the browser itself and that are just no endpoints for these kind of functions.
What you could do is make an array in js to store previous locations and before you update your view test against that array to see if you got a stale location.
You do have this ability now.
getCurrentPosition takes three parameters: success, failure and options
Try this:
<script>
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(handlePosition, (error)=>{}, {maximumAge:0});
}
function handlePosition(pos) {
//this passes lat/long to additional code
}
</script>
Related
I am currently trying to build an app for employees to clock on and off from work each day.
I have currently setup geolocation to automatically get the location of the user and store it in a database however for obvious reasons if a user presses deny it cannot get the location.
Is there a way I can force location to be on for my page or prevent the page from loading if location is disabled.
I have managed to set this up with a function but if the user presses a not now button or select later the page still renders correctly and does not prevent the employee using the system.
What I need to do are the following:
Force Location Services to be on or Prevent the page from rendering if they are off
Bring up the allow/deny location services box on page load if they have previously denied their use.
Any help would be greatly appreciated.
I don't know how you're generating your page, but if you can rely on Javascript to render, or if redirecting to an error page in case of a denial is acceptable, you can use rely on the fact that you'll get an error callback in case of a denial:
navigator.geolocation.getCurrentPosition(success[, error[, options]])
So you site could either:
Only render if the success handler is called and show the error if not (after timeout)
Redirect to an error page if the error handler is called
Now, to your "clear denial", I doubt this is possible. The best I can suggest is that you have instructions on clearing the geo settings on the error page. These will depend on OS and browser, unfortunately.
Once user denies, you can not get the lat/lng. This is enforced by the browsers. Another option is to get the IP address of the user as the fallback to map it to the physical address. But do take note, this approach works better when user is connecting to wifi. The accuracy for 3G/4G is at zip code level.
The format for geolocation is
navigator.geolocation.getCurrentPosition(success, error, options)
You can check if user prevented the location prompt by following way
navigator.geolocation.getCurrentPosition(
function(position) {
// Success goes here
}.bind(this),
function(error) {
toastr.error("Please turn on location for this feature")
setTimeout(function() {
window.location.href = '/'
}, 2000)
}, [your options]
)
Unstable connection in a normal browser is not a major issue because the user can click on the "reload button" if the page didn't load properly. In phonegap there is no such button, so we have to make sure everythings loads correctly 100% of the time.
I experience a problem because when connection is unstable during the initialisation of a google service (places autocompletion, geocoding or map display), no error message is thrown and yet the service will NOT work.
First we initialize google services
//In this senario the internet connection is good and stable
$('body').append('<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&v=3.exp&callback=googleCallback"></script>');
Then we want to use the google places autocomplete service and here is a scenario that is reproducible :
//At this point we lose the internet connection
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
//At this point autocomplete is defined and not empty, no error thrown
//At this point the internet connection come back
//At this point the autocomplete box is not working
Note that this "bug" also occurs for geocoding and map display.
The first part of my question is : how can i at least detect in my code that the initialisation of the (autocomplete or geocoding or display map) service didn't work properly.
Now we would like to reload the places autocomplete because internet is back and we need the service
//From now on the connection is good and stable
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
//We get no error but the autocomplete box still does not work
Here is the only way i found to get the places autocomplete service to work after connection loss occured as shown in scenario 1
//From now on the connection is good and stable
$('body').append('<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&v=3.exp&callback=googleCallback"></script>');
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
//At this point the autocomplete box is working properly
So the second part of my question is, do i really have to reload the hole google maps javascript api when 1 particular service failed to initialize ?
To reproduce the bug you can follow that link, it is referenced as problem 3.
If you're intersted in problem 1 you can check this question
If you're intersted in problem 2 you can check this question
I'm developing a web app for mobile and using html5's geolocation api.
When the page is loaded I start a watch position:
function enableWatchPosition() {
if (navigator.geolocation) {
watchPositionId = navigator.geolocation.watchPosition(locateByBrowser, handleErrorGettingLocation, {
timeout : 30000,
enableHighAccuracy : true,
maximumAge : 1000
});
}
}
If a user doesn't have his GPS on, handleErrorGettingLocation is triggered and I show him an error message, asking him to turn GPS on.
My Question is:
Suppose the user then turns his GPS on - how can I detect that (so I could retry and call enableWatchPosition() again)? Is there some sort of js event I can listen to?
Thanks!
There is no such event that’s exposed in a way you could see from your Web-application code. Certainly there is no such event defined in the standard Geolocation API spec. And I don’t believe there are any non-standard events that any browsers expose for it. So I don’t think you’re going to be able to automatically re-trigger a call to your enableWatchPosition() function.
I’m sure that’s not the answer you were hoping for, but it is the answer. :-(
I am using the 'chrome.storage.sync.get/set' to save my data. My question is, will the data saved using this API will get reset when I close chrome browser window and open it again. Is there any method to clear the data saved when we exit from chrome? I know there is a method 'chrome.storage.sync.clear()'. But this should happen only when the user exits from chrome.
will the data saved using this API will get reset when I close chrome browser window and open it again
No, it's saved — not just locally, but also potentially synced to the user's Google account. That's the point of the sync storage area. The documentation says sync is like localStorage, but synced to the user's account.
If you're using it for transient data, don't. Use local instead (as there doesn't appear to be an extension equivalent of session storage) or perhaps just store the data in your extension's runtime environment (it's not clear what you're using this for).
I know there is a method chrome.storage.sync.clear(). But this should happen only when the user exits from chrome.
You'd have to trigger clear from an event. Unfortunately, there is not currently an official way for an extension to get notified when Chrome closes (there's an open issue on it). Hopefully there will be a way at some point, but there isn't currently.
You're right chrome.storage.sync.clear(), removes all storage from sync. However, if you want to use that function when the browser 'exists', you'll have to look at the Processes Api.
You would probably want to use this function (from the documentation) :
chrome.processes.onExited.addListener(function(){...});
It takes processId as one of the arguments. So you would just have to get hold of the processId for the browser process. I found a relevant answer for this on SO only. It suggests you do something like:
//Basically loop through all the processes to get the browser's Process Id
var browserId;
chrome.processes.getProcessInfo([], false, function(processes) {
processes.forEach(function(process) {
if (process.type === 'browser') {
browserId = process.id;
}
});
});
Once you have the browser's Process Id, you can add a listener to the exit event and do the needful. I hope it gets you started in the right direction.
The website I'm working on uses HTML5 geolocation api. It works fine, but I need to know if the feature has been authorized.
navigator.geolocation only tells if the feature is available. What I want to know is whether the user has enabled it already. Basically, I need to know if the browser will request permission to use the feature. Is it possible?
If the user does not allow your app to use the Geolocation API the methods getCurrentPosition and watchPosition will return an PositionError object via the error callback:
void getCurrentPosition(successCallback,
errorCallback,
options);
long watchPosition(successCallback,
errorCallback,
options);
The PositionError looks like:
PositionError {
code;
message;
};
where the possibles values of code are:
PositionError.PERMISSION_DENIED = 1;
PositionError.POSITION_UNAVAILABLE = 2;
PositionError.TIMEOUT = 3;
And more specific:
PERMISSION_DENIED (numeric value 1)
The location acquisition process failed because the document does not have permission to use the Geolocation API.
The documentation here.
There is no check for permanent authorization.
The only thing you can do imho is try to "guess" if the user has authorized by estimate time.
For example:
more than 1,5 seconds to retrieve geolocation -> probably user got to
click interface and give auth
less than 500ms -> pretty sure user already give auth