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
Related
I've used below code to detect the current location in angular app. this is working fine with all the desktop browser but it not working in mobile device please find below code for more understanding.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onPositionUpdate,locNotFound,{frequency:5000,maximumAge: 0, timeout: 100, enableHighAccuracy:true});
} else {
// nothing
}
function locNotFound () {
console.log('location not found');
}
function onPositionUpdate(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=true";
$http.get(url)
.then(function(result) {
console.log(result);
});
}
As you can see that locNotFound() function is called in mobile device. which it should not do because GPS on in mobile device.
I just can give you a partial answer for Android.
Please open the Chrome Browser at Android, click at the icon top right (the tree dots), click at Settings, click at Site Settings and please check the settings for Location. As far as I know this is disabled per default.
So I think your problem is related to security restrictions
Regards
Michael
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;
});
I have been working on an app that uses the getCurrentPosition(), but that doesn't work anymore in the latest version of Chrome, see:
Deprecating Powerful Features on Insecure Origins
So my code here doesn't work in latest stable version of Chrome:
var latitude = 0;
var longitude = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
$("#data").html("latitude: " + latitude + "<br>longitude: " + longitude);
});
}
What are alternatives to getting the user's position with HTML Geolocation API? Any thoughts?
I'm grappling with this myself. If HTTPS is not an option for you, then maybe add a fallback for Chrome where you prompt the user to submit their address. Then have your app geocode it.
I've got a angular application that displays records, and gives the user the ability to add records.
Everything works perfect on desktop or iOS devices, but on android devices, the POST method fails(403 - forbidden).
this is the code in my service:
obj.getRecords = function() {
return $http.get(serviceBase + 'records');
};
obj.getRecord = function(id) {
return $http.get(serviceBase + 'record/' + id);
};
obj.saveRecord = function(record) {
return $http.post(serviceBase + 'record', record);
};
Anyone experienced with this problem?
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
might fix your problem.
Reference: Angular docs
I could imagine that it could have to do with an apple touch icon that is integrated into your site. I had it once that it missing (even if iPhones worked!) caused redirection to another site with another session id. This also caused a 403. It's just an idea though. It seems that the Android browser has some other way of retrieving the touch icon which is the error's cause.
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