I'm building a node app that returns the user's geolocation, but I'm having a hard time testing it because I can't access geolocation on my computer. I tried using my localhost server in both Firefox and Chromium - Firefox asks for my permission but then can't retrieve it, and Chromium doesn't even get that far. When I deploy it to Heroku, I still can't access it on the computer. On my iPhone, Firefox still has no luck but Safari can do it. I don't know if my problem is in Ubuntu itself (can it block things like that?) or if both Firefox and Chromium have the same issue.
I doubt my code will be especially useful, but here it is anyway:
const locationButton = jQuery('#send-location');
locationButton.on('click', function() {
if (!navigator.geolocation) return alert('Geolocation not supported by your browser.');
navigator.geolocation.getCurrentPosition(function (position) {
socket.emit('newLocationMessage', {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}, function (mapLink) {
alert(mapLink);
});
}, function () {
alert('unable to fetch location.')
});
});
The app is also up at http://rocky-brook-97128.herokuapp.com/.
Thanks for any guidance on this!
As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.
Try it on https.
https://rocky-brook-97128.herokuapp.com/
(1) In a new tab, type or paste about:config in the address bar and press Enter/Return.
(2) In the search box above the list, type or paste geo and pause while the list is filtered
(3) If the geo.wifi.uri preference is bolded and "modified" or "user set", you can right-click > Reset it to the default
If Firefox sends anything to the geolocation service, the address should appear in the Browser Console
You can inspect and manage the permissions for all domains on the about:permissions page
Related
I'm currently facing a really difficult bug on my code. This code works on my MacOS (on firefox, opera, safari and chrome) and also works on another Windows machine I have. However it doesn't work on a friend's computer using Windows, with Opera, Chrome or Edge.
What the code does is:
A user clicks on a button
I open a popup for a third party website
that redirects me back to my site with a code on the url
I use that code to fetch my server that fetches an api for the user info
I receive that info on the popup and save it to localStorage
The main window detects that there was a store event and displays the user information
The bug can manifest in the following ways:
The popup is force closed (even if no windows.close function is
triggered)
Even if the data is stored in the popup and I can see it
there, it doesn't show up on the main window storage
I have tried postMessage instead of localStorage and it works better than localStorage. Using postMessage the bug doesn't manifest itself using the private mode of Opera on Windows.
I tried using Cookies but they don't fit my use-case because I need to save the user image and it's too big for a cookie.
I also tried opening up a new tab instead of a window and the bug persists.
I have always cleared the cache and localstorage. I also had extensions disabled. Both the main website and the popup are on the same domain and protocol. The diference is the popup that is under /redirect?code=xxxxxxxx
Another weird fact: We had two different branches for this project on git: 'master' and 'develop'. Both published on heroku, and 'develop' had no bug on my friends pc. 'develop' was ahead of 'master' with no conflicts, we merged and the bug appeared on the 'master' website.
page.js (the main window)
function loginButtonAction(event) {
window.open(fenixRequestUserPermissionURL, '_blank', 'width=750,height=675');
fenixLoginButton.classList.add('is-loading');
window.addEventListener('storage', function() {
var userData = JSON.parse(localStorage.getItem('fenix-user'));
registerUser(userData);
localStorage.removeItem('fenix-user');
});
event.preventDefault();
fenixLoginButton.removeEventListener('click', loginButtonAction);
}
fenixLoginButton.addEventListener('click', loginButtonAction);
popup.js (the window to which the first link redirects to)
window.addEventListener('load', function() {
var params = new URL(window.location.href).searchParams;
if (params.has('code')) {
var code = params.get('code');
fetch('/fetchInfo/' + code)
.then(function (response) {
return response.json();
})
.then(function(received) {
localStorage.setItem('fenix-user', JSON.stringify(received));
window.close();
}).catch(function(error) {
console.warn(error);
});
}
});
The bug is silent, there are no errors on any of the consoles. Thank you for reading until here!
I am trying out geolocation in Javascript, writing a very small web app on codepen. I mainly use Safari (10.1.2) on my macbook (10.12.6) and I couldn't get the following geolocation code working :
navigator.geolocation.getCurrentPosition(function(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
getRequest(latitude, longitude);
}, function(error) {
console.log(error.code);
});
After some time I opened up Chrome and tested the same code, it worked. I started doing some research on Safari and geolocation and have seen some people mention wired connection being the culprit.
I tried with wifi and indeed, it works. I don't know why, and couldn't find an explanation anywhere, but Safari refuses to handle geolocation when connected via Ethernet.
I did the same test on Google Maps and geolocation works everytime. So I thought maybe my code is wrong but I have the same trouble with code from W3Schools. I'm guessing Google uses another method.
How can I make it work on Safari with a wired connection ? I'm surprised to find posts from 2010 and to be facing the same problem 7 years later with all software up to date. Is there a universally compatible method I'm missing ? I'm wondering how services depending on geolocation handle this problem.
Thanks in advance for your help.
I'm writing my web application on React/Redux. And I need to get user location with a help of Geolocation API. On desktop browsers everything works fine, but on mobile phones (checked out on Xiaomi Redmi Note 3 and iPhone 5s) it throws error code 1 - permission denied. And it doesn't requests any permissions to get the location.
Here's a test sample which I ran on my site:
componentDidMount() {
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(position => {
alert(position.coords.latitude + ' ' + position.coords.longitude);
}, err => {
alert('ERROR: ' + err.code);
});
} else {
alert('Geolocation API is not supported!');
}
}
What's the solution of this problem?
Got the same Problem... Solved:
Check your phone permissions for sharing your location.
On iPhone:
Settings -> Location Services -> [your Browser]
https://support.apple.com/en-ca/HT203033
Added:
Chrome requires https for geolocation usage:
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
I've got the solution. I'm using the Web Application Manifest and it needed to set the permission to use Geolocation API.
We just need to set an "required_features" option at manifest.webapp file:
{
"required_features": ["geolocation"]
}
Hope it will be useful for somebody ;)
As of the Year 2021, this still does not work.
This is the link in that error message.In case you're wondering, it talks about "prefer secure origins for powerful new features" and location is consider one of those powerful features.
To generate the above, update the error section as follows:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
// other
},
err => {
// include the "code" part
alert(`ERROR(${err.code}): ${err.message}`)
});
};
On desktop during development...It works because if you read from the above link you will note that localhost is considered a secure origin.
In fact, even the chrome link shared in #chrisheyn's answer above, there is a section "Does this affect local development?" and explains why this should work on locahost.
So how about Mobile during development?Notice that react serves the app over your network e.g. http://192.168.0.134:3000 and that is definitely not considered a "secure origin" at all.
This question "Can I detect at runtime if the geolocation was blocked because of not being on a secure context
" mentions that... Errors due to this secure-context issue will return a code of 1 which is a "Permission Denied Error".
What's the solution?
Until the react team updates how your mobile picks the app during development, there is absolutely nothing you can to solve this issue.
To use the HTML5 Geolocation API, you will need to run the app over HTTPS. This means push your app to the cloud/host (in order to test this feature) or if you can some manage to get this network url http://192.168.0.134:3000 to do https The latter option, i believe, is much harder but I'd be interested to know if someone pulls it off.
I am using following code:
var fail = function(error) {
alert("Unable to get location");
};
function getGeo() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
success,
fail,
{maximumAge: 50000, timeout: 30000, enableHighAccuracy: true});
}
};
Mostly It works but often it gives geolocation error and unable to get coordinates.
How can I make possible to get coordinates no matter browser window is inactive or browser is in background or mobile itself in sleep mode?
Without specifics of "geolocation error" my answer can no be complete but: -
At present you cannot get coordinates if browser window is inactive or browser is in background or mobile itself in sleep mode, unless you are developing a hybrid App with something like phonegap/cordova. (Firefox has the exception of continuing to service watchPosition() if the App is foregrounded but the phone is asleep.)
I have made several suggestions to W3C, IETF, Chrome Dev, Mozilla Dev, and Edge Dev regarding a workable solution using the Service Worker Extensibility functionality for a Javascript-only solution.
Briefly, the UA tracks Geolocation changes and if within range of a dev supplied filter, a ServiceWorker will be instantiated which may foreground the App or merely notify the App Server.
Please pursue this issue with the relevant bodies as the idea is beginning to gain traction.
HTH
Using the following code, I am receiving the following errors:
the pipe is being closed
and
the wait operation timed out
Code:
var loc = new Windows.Devices.Geolocation.Geolocator();
loc.getGeopositionAsync().done(function (pos) {
console.log(pos);
});
I am running this within the Windows 8 simulator, and have attempted both with the Simulated location enabled and disabled.
What is causing this error, and what is the correct manner in which to use the Geolocator to successfully retrieve the users location both on a real GPS enabled device, and in the simulator?
Your code works fine for me, both on my local machine and in the simulator, on Windows 8 Release Preview.
I tested it in the simulator both with the simulated location on and off.
One thing to check...do you have Location enabled in the Capabilities section of your app manifest?
Also, you may want to try writing the location info to the screen...the code above will simply pass the pos object to the console, so you wouldn't actually know if it was returning correct geolocation information even if you get past the error.
Here's what I did:
Start with a new Blank JavaScript app.
open default.html, and add an id of "geo" to the <p> tag containing the default content.
Add the following code to the app.onactivated handler to test (I added my code just before the closing brace:
var loc = new Windows.Devices.Geolocation.Geolocator();
loc.getGeopositionAsync().done(function (pos) {
console.log(pos);
var geo = document.getElementById("geo");
geo.innerText = pos.coordinate.latitude + ", " + pos.coordinate.longitude;
});
The machine I'm testing on is a laptop with no GPS, so the underlying API will use WiFi or IP address info for the geolocation. If GPS is available, it should be used for the location data transparently to your app.