javascript - geolocation not working in codepen

随声附和 提交于 2019-12-12 10:55:10

问题


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?


回答1:


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.




回答2:


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!




回答3:


Starting with Chrome 50, Chrome stopped supporting geolocation on unsecured protocols. https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only



来源:https://stackoverflow.com/questions/38066541/javascript-geolocation-not-working-in-codepen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!