openweathermap.orgからJSONデータを取得しようとしていますが、$ .getJSONは機能しません。 ブラウザからAPIを呼び出すと、JSONデータが表示されますが、JSファイルでは機能しません。Weather APIを取得できません
$(document).ready(function(){
$("#button").click(function(){
navigator.geolocation.getCurrentPosition(location,error,{timeout:10000});
});
function location(pos){
$("#crd").html("Location: " + pos.coords.latitude + " , " + pos.coords.longitude);
$.getJSON("api.openweathermap.org/data/2.5/weather?lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&APPID=key", function(json){
$("#weather").html(JSON.stringify(json));
});
}
function error(err){
var errorCode = "";
switch(err.code) {
case err.PERMISSION_DENIED:
errorCode = "User denied the request for Geolocation.";
break;
case err.POSITION_UNAVAILABLE:
errorCode = "Location information is unavailable.";
break;
case err.TIMEOUT:
errorCode = "The request to get user location timed out.";
break;
case err.UNKNOWN_ERROR:
errorCode = "An unknown error occurred.";
break;
}
$("#crd").html("Error " + err.code + ": " + errorCode);
}
});
もう1つ問題があります。 http://を追加するとlocalhostで動作しますが、codepenでは動作しません。何か案が?
私はcodepenにあなたがあなたがshemeを逃しているhttps://cors-anywhere.herokuapp.com/
あなたがのためのアドレスを固定する必要がありますそれは別のドメインを適切に参照するためです。これを行うには、開始時(オプションでプロトコル)に '/ /'を追加することで可能です - '' //api.openweathermap.org/... "'。それ以外の場合、アドレスは現在のページとの相対的な扱いとなり、 'api.openweathermap.org'は有効なディレクトリ名となります。 –
スキーム( 'http://'や 'https://'、あるいは現在のスキームを使うのに '//')を含む完全なURLを使用するとよいでしょう。 – jcaron
あなたのお気に入りのブラウザのインスペクタ/開発ツールでのリクエストは、おそらくかなり早く問題を強調していたでしょう。 – jcaron