0

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 には何も表示されない理由がわかりません。

どんな助けでも大歓迎です。

4

1 に答える 1

1

これnavigator.geolocation.getCurrentPositionは が非同期であるために発生するため、解決策の 1 つは、場所が見つかったとき (またはエラーがスローされたとき) に呼び出されるコールバックを渡すことです。

alertスクリプトが場所を認識する時間を与えていたため、 を使用して正しい結果が表示されていました。

1 つの解決策は、次のように呼び出したnavigator.geolocation.getCurrentPositionコールバックにコードを移動することです。findPosition

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";
  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);
}  

if(navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(findPosition);
}
于 2013-06-05T09:10:25.063 に答える