(私はGoogleマッププロジェクトで働いています) 私はhell関数にlatlonの可変フォーム関数showPositionを渡そうとしていますが、私は傾けません。一つの関数から別のjavascriptに変数を渡します。
私がshowPosition関数でlatlonを印刷すると、すべてが機能します。 hello関数でlatlonを表示すると空白のページが表示されます。
var latlon;
window.onload = function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
/*document.write (latlon); */
}
function hello() {
variablelatlon = latlon;
document.write (variablelatlon);
}
showPosition();
hello();
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
私はこれに私のコードを変更します。しかし、私は結果として任意の座標を参照してください。
var x = document.getElementById("demo");
var coordlat;
var coordlng;
window.onload = function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
coordlat = position.coords.latitude;
coordlng = position.coords.longitude;
}
function hello() {
document.write (coordlat);
document.write (coordlng);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
showPosition();
hello();
よく 'showPosition()'は 'hello()'を呼び出すことはありません、そして 'hello()'は入力パラメータを受け取るように設定されていません。 'latlon'は' showPosition() 'のローカル変数です。つまり、そのスコープ内でのみ参照可能です。それを渡すか、グローバルにアクセス可能なものに書き込む必要があります。 – Utkanos
showPosition()を呼び出すときに、 'position'パラメータが渡されていません。また、showPosition()は 'latlon'という名前のLOCAL変数を宣言しています。つまり、グローバルな 'latlon'変数を設定しません。これは、hello()関数がタッチされていないグローバルな 'latlon'変数にアクセスすることを意味します。 – Code4aliving
[document.write'](http://stackoverflow.com/q/802854/1048572)も使用してはならないことに注意してください。 – Bergi