GeoLocation API に問題があります。基本的に、ユーザーの場所に基づいて (埋め込みではなく) Google マップにリンクしようとしています。地理位置情報を使用できない場合は、デフォルトで目的地のみが表示されます。私が抱えている問題は、コードにアラートを入れない限り、デフォルトで常に宛先のみになることです。
これが私のコードです:
function findPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
mapURL = "https://maps.google.co.uk/maps?saddr=" + latitude + "," + longitude + "&daddr=50.795251,-1.107136&sensor=TRUE";
alert("1 " + mapURL); // Alert shows the URL correctly
}
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(findPosition);
}
alert("2 " + mapURL); // Shows empty string as if findPosition() has not been called???
alert("3 " + mapURL); // Shows mapURL correctly
if (mapURL == "")
{
// Set the default URL with only the destination
mapURL = "https://maps.google.co.uk/maps?q=50.795251,-1.107136";
}
var link = "<a href=\"" + mapURL + "\" style=\"text-decoration:none;color:#000;\" target=\"_blank\">";
document.write(link);
//-->
</script>
アラートの横にあるコメントは、コードがどのように動作するかを示すためのものですが、アラートが削除されると、常に宛先のみのデフォルト URL が設定されます。
アラート 1 の後に処理する必要があるにもかかわらず、アラート 1 には正しい URL が表示されているのに 2 には何も表示されない理由がわかりません。
どんな助けでも大歓迎です。