navigator.geolocation.getCurrentPosition/watchPosition is not working in android 6.0 - javascript

Here is my javascript code :
function getLocation() {
//navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:30000, enableHighAccuracy:true});
var mobile =jQuery.browser.mobile;
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if(mobile){
watchLocation(function(coords) {
var latlon = coords.latitude + ',' + coords.longitude;
//some stuff
}, function() {
alert("error");
});
} else {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("error");
}
}
}
function watchLocation(successCallback, errorCallback) {
successCallback = successCallback || function(){};
errorCallback = errorCallback || function(){};
// Try HTML5-spec geolocation.
var geolocation = navigator.geolocation;
if (geolocation) {
// We have a real geolocation service.
try {
function handleSuccess(position) {
alert("position:"+position.coords);
successCallback(position.coords);
}
geolocation.watchPosition(handleSuccess, errorCallback, {
enableHighAccuracy: true,
maximumAge: 5000 // 5 sec.
});
} catch (err) {
errorCallback();
}
} else {
errorCallback();
}
}
I have tried both getCurrentPosition and watchPosition.
It's reaching errorCalback() method when control comes to geolocation.watchPosition line.
I am testing in Motorola G 2nd Gen with Android 6 and Google chrome browser and opera mini.
Update 1: When I put alert in error call back function I got error:1; message:Only Secure origins are allowed(see:link).
navigator.geolocation.getCurrentPosition(showPosition, function(e)
{ alert(e); //alerts error:1; message:Only Secure origins are allowed(see: )
console.error(e);
})
Update 2: With the help from g4s8 I am able to findout that the error is because of insecure URL. i.e only accessing with http instead of https.But then also I bypassed that in browser by clicking advanced button.But it will prompt for Do you want to allow location, which I don't want..is there any way to access location without prompting it?

Your page should be served over https to access geolocation API.
See Geolocation API Removed from Unsecured Origins
Starting with Chrome 50, Chrome no longer supports obtaining the user's location using the HTML5 Geolocation API from pages delivered by non-secure connections
...
It is an important issue as it will directly impact any site that requires use of the geolocation API and is not served over https
To fix this serve your page over https or on localhost.
Thank you...Is there any way to bypass it??
You can try to use some geolocation services, e.g.
geoip2, Geolocation request
how to use them? can you show an example?? from those two can i access user location without knowing them?
GeoIP2 detect you location by ip address. You can obtain country (geoip2.country()) and city (geoip2.city) with js lib:
<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
Here https://dev.maxmind.com/geoip/geoip2/javascript/ you can find full documentation.
Google maps geolocation is google service, so you need to get api key first. Then you can send POST request with json parameters to https://www.googleapis.com/geolocation/v1/geolocate?key=API_KEY and get the response:
{
"location": {
"lat": 51.0,
"lng": -0.1
},
"accuracy": 1200.4
}
where location is the user’s estimated latitude and longitude, in degrees,
and accuracy is the accuracy of the estimated location, in meters.
Full json parameters defenition you can find in "Request body" section here https://developers.google.com/maps/documentation/geolocation/intro#overview
Also you can find useful those answers: getCurrentPosition() and watchPosition() are deprecated on insecure origins
using IP it provides only country and city..??
Yes, only this.
will it provide physical location like how getCurrent Position provides??
No, you can't get physical location, because it can be accessed only via gelocation API, that was restricted in insecure context.
Also you have one more option. You can host only one page (that access geolocation API) on https server, and redirect from this page to your http site with user location in get parameters.
/* https page */
navigator.geolocation.getCurrentPosition(function (result) {
window.location.href = "http://your.site.com/http-page?lat=" + result.latitude + "&long=" + result.longitude;
});

Related

Getting a 403 error when using Youtube API V3

We have a website that use Youtube API V3 in order to display youtube video. We haven't used that website for a while and somehow all of the sudden, we're getting the following error:
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. YouTube Data API has not been used in project 1234567890 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=1234567890 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
"extendedHelp": "https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=1234567890"
}
],
"code": 403,
"message": "Access Not Configured. YouTube Data API has not been used in project 1234567890 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=1234567890 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
}
}
So looking on similar error on the web, we found plenty but none of the solution worked for us. Here is what we did so far:
Regenerate a key (didn't work)
Remove all kinds of restrictions and allow everything * (didn't work)
Erase previous API key and create a new one without any restriction (not working either)
Looking at the dashboard, we can tell that the new key is making a request to the API but somehow we keep continue getting this same error.
Now we're stuck and don't know what else to do. Any idea ?
Thanks a lot for your help.
EDIT
Here is how we're calling the API url (AngularJs project):
function getDurationFrom (videoId, callback) {
var uri = 'https://www.googleapis.com/youtube/v3/videos?id=' + videoId + '&part=contentDetails&key=' + YOUTUBE_API_KEY;
$http.get(uri).then(function (response) {
var metadata = response.data;
if (metadata.items.length > 0) {
var duration = metadata.items[0].contentDetails.duration;
if (callback) {
callback(duration);
}
}
});
};

javascript - geolocation not working in codepen

I'm trying to implement a simple weather app in codepen. The app works fine on localhost
It asks for permission to use navigator.geolocation and if accepted it shows the weather,
but on codepen it's not even asking for permission.
here is the link
http://codepen.io/asamolion/pen/BzWLVe
Here is the JS function
function getWeather() {
'use strict';
$('#getWeatherButton').hide();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var url = 'http://api.openweathermap.org/data/2.5/weather?APPID=53ac88144e6ee627ad0ed85277545ff9';
// var url = 'example.js';
var apiCall = url + '&lat=' + position.coords.latitude + '&lon=' + position.coords.longitude;
// window.location.href = apiCall;
$.getJSON(apiCall, function (json) {
setSkycon(parseInt(json.weather[0].id, 10));
$('#location').html(json.name + ', ' + json.sys.country);
var temp = (Math.round((json.main.temp - 273.15) * 100) / 100);
$('#temp').html(temp + '<span id="degree">°</span><span id="FC" onclick="convert()">C</span>');
$('#condition').html(json.weather[0].main);
});
});
}
};
Can anybody tell me why codepen is not asking for permission?
I had this same problem on the same challenge. Simply prepend your codepen with https instead of http and you'll be fine.
Like this:
https://codepen.io/crownedjitter/pen/AXzdvQ
if you want to use this:
navigator.geolocation.getCurrentPosition();
in Chrome.
According to the console in Chrome:
getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS.
There's more details here: https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins Essentially Chrome only wants to send location information over HTTPS. However, in order to allow developers to test they treat localhost as if it were a secure network. Hope this helps!
Starting with Chrome 50, Chrome stopped supporting geolocation on unsecured protocols.
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only

Geolocation doesn't work with cordova

I'm currently working on a mobile application with Intel XDK (In background it's Cordova finally, that's why I put Cordova in title.)
With an Ajax request, I get some adresses and with these adresses I want to calculate the distance between them and the current position of user.
So, I get adresses, I convert them and I make the difference.
But actually, nothing is working !
function codeAddress(id, addresse) {
geocoder.geocode( { 'address': addresse}, function(results, status) {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function(){}, 100);
}
console.log(id);
console.log(addresse);
//document.addEventListener("intel.xdk.device.ready",function(){
if (navigator.geolocation)
{
if (status == google.maps.GeocoderStatus.OK)
{
navigator.geolocation.getCurrentPosition(function(position) {
addressEvent = results[0].geometry.location;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var position = new google.maps.LatLng(pos.lat, pos.lng)
var resultat = google.maps.geometry.spherical.computeDistanceBetween(addressEvent, position);
console.log(resultat);
console.log(addressEvent);
console.log(pos);
console.log(position);
var convert = Math.floor(resultat);
var finalConvert = convert + " m";
var distance = document.createElement('span');
distance.innerHTML = finalConvert;
distance.className = "geo";
document.getElementsByClassName('meta-info-geo')[id].appendChild(distance);
}, function() {
handleLocationError(true, infoWindow);
});
}
}
//},false);
});
}
In the console.log(id), console.log(addresse), I HAVE results !
Actually i'm getting 4 IDs and 4 adresses.
I checked on all the topics I could find on StackOverFlow, and I had normally to add the line in // with the addEventListener but it changes nothing.
Is there someone who knows how to change that ?
ps : Of course, cordova geoloc is in the build and permissions are granted !
EDIT : I'm targeting Android 4.0 min and iOS 5.1.1. I'm using SDK.
EDIT 2 :
Geolocation frequently does not work the way people expect it to work, for a variety of reasons that have been expressed here and here.
You can experiment with geo by using the "Hello, Cordova" sample app that is in the XDK and also available on GitHub. Try using it on a variety of devices to see how things work. Push the "fine" button to initiate a single geo call for a "fine" location and push the "coarse" button to initiate a single geo call for a "coarse" location. Push the "watch" button to initiate a request for a series of geo data points (set to coarse or fine by pushing one of the single buttons first).
The behavior you get in the Emulate tab will be dramatically different than what you get on a real device. The type of device (Android, iOS, etc.) and the version of that device will influence your results; the manufacturer of the device and your location (inside or outside) will influence your results. Do not assume that making a call to the geo APIs will always give you immediate and reliable data, geolocation hardware does not work that way... In fact, you cannot assume that you can even get a valid result! See the two links I pointed to earlier in the post for some reasons why.

ask for geolocation permission again if it was denied

im building an app through phonegap, with a geolocation button.
if a user denies permission for geolocation the first time, how can i ask for permission again when they click the geolocation button again?
my code structure at the moment is:
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, positionError);
} else {
hideLoadingDiv()
showError('Geolocation is not supported by this device')
}
}
function positionError() {
hideLoadingDiv()
showError('Geolocation is not enabled. Please enable to use this feature')
}
You can't.
The only thing you can do is to display the instructions to reactivate the location sharing in his browser's settings (https://support.google.com/chrome/answer/142065?hl=en).
Two ways of doing this:
If you have a version of Chrome bigger than 83.0.4103.97 then use the lock icon in the URL
For older versions of Chrome the bellow code will work fine:
The bellow code only works on Chrome.
Steps:
Open Chrome
Open the console
Copy in the console
var allowGeoRecall = true;
var countLocationAttempts = 0;
Copy in the console the functions
function getLocation() {
console.log('getLocation was called')
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,
positionError);
} else {
hideLoadingDiv()
console.log('Geolocation is not supported by this device')
}
}
function positionError() {
console.log('Geolocation is not enabled. Please enable to use this feature')
if(allowGeoRecall && countLocationAttempts < 5) {
countLocationAttempts += 1;
getLocation();
}
}
function showPosition(){
console.log('posititon accepted')
allowGeoRecall = false;
}
Run the function in the console
getLocation();
After running this you will be asked to allow to share your position. If your response is negative you will be asked again until you agree.
HINT: If your user has a negative response, let him know why you need the coordinates. Is vital for him to understand that this step is vital for the good run of the web app.
This can be reset in Page Info which can be accessed by clicking the lock icon next to the URL and allowing Location

W3C Geolocation API not working in Chrome

The below code works in Firefox but not in Google Chrome:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script type="text/javascript">
var successCallback = function(data) {
console.log('latitude: ' + data.coords.latitude + ' longitude: ' + data.coords.longitude);
};
var failureCallback = function() {
console.log('location failure :(');
};
var logLocation = function() {
//determine if the handset has client side geo location capabilities
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(successCallback, failureCallback);
}
else{
alert("Functionality not available");
}
};
logLocation();
setTimeout(logLocation, 5000);
</script>
</head>
<body>
<p>Testing</p>
<body>
</html>
What's going on? I thought Google Chrome was supposed to support the W3C Geolocation API.
Works perfectly for me - with both Chrome 11 and Firefox 4.0.1 on Win 7
Make sure you've not disabled location tracking in Chrome: Options > Under the Hood > Content Settings > Location
Because of security restrictions, resources loaded with the file:/// scheme are not allowed access to location. See HTML 5 Geo Location Prompt in Chrome.
If your domain is insecure (e.g. HTTP rather than HTTPS) then you are not allowed access to location in Chrome. This is since Chrome version 50 (12PM PST April 20 2016).
See https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only for details.
in 2017 :
Note: 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.
Geolocation API Removed from Unsecured Origins in Chrome 50
It works fine for me - with both Chrome 11 and Firefox 4.0.1 on Win 7
Make sure you've not disabled location tracking in Chrome: Options > Under the Hood > Content Settings > Location please allow the permission
and after checking the permission please run it
after running either it will be sucesscallback or else it comes to errorcallback
function sucesscallback (position)
{
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: userLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapObject = new google.maps.Map(document.getElementById("googleMap"), myOptions);
var marker = new google.maps.Marker({
map: mapObject,
position: userLatLng
});
}
function failureCallback(error) {
switch (error.code) {
case 1:
alert("User denied the request for Geolocation.");
break;
case 2:
alert("Location information is unavailable. Please ensure Location is On");
break;
case 3:
alert("timeout");
break;
case 4:
alert("An unknown error occurred.");
break;
}
}
<div id='googleMap' style='width:300px;height:300px;'>
</div>
The Geolocation API lets you discover, with the user's consent, the user's location. You can use this functionality for things like guiding a user to their destination and geo-tagging user-created content; for example, marking where a photo was taken.
The Geolocation API also lets you see where the user is and keep tabs on them as they move around, always with the user's consent (and only while the page is open). This creates a lot of interesting use cases, such as integrating with backend systems to prepare an order for collection if the user is close by.
You need to be aware of many things when using the Geolocation API. This guide walks you through the common use cases and solutions.
https://developers.google.com/web/fundamentals/native-hardware/user-location/?hl=en

Categories