简体   繁体   中英

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">&deg;</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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM