2013-05-26 51 views
1

我想使用javascript獲取經度和緯度,並且比較它與以前的位置。當您從另一臺計算機登錄時,Facebook就會執行某些操作,但要簡單得多。爲了實現這一點,我創建了2個隱藏字段,並且當用戶提交表單時,值將被髮送到服務器。從JavaScript獲取位置並將其傳遞到PHP

<body> 
<p id="log">Login to continue: 
    <form action="welcome.php" method="post"> 
     Username: <input type="text" name="user" required > 
     Password: <input type="password" required> 
    <input type="hidden" name= "longitude" id="longitude"> 
    <input type= "hidden" name ="latitude" id="latitude"> 

    <input type="submit" name="submit" onclick="getLocation()"> 
</p> 
<script> 
var x=document.getElementById("log"); 
function getLocation() 
    { 
    if (navigator.geolocation) 
    { 
    navigator.geolocation.getCurrentPosition(showPosition); 
    } 
    else{x.innerHTML="Geolocation is not supported by this browser.";} 
    } 
function showPosition(position) 
    { 
    var latitude = position.coords.latitude; 
    var longitude = position.coords.longitude; 
    document.getElementByID("longitude").value = longitude; 
    document.getElementByID("latitude").value = latitude; 

    } 

</script> 

但在的welcome.php的代碼:

$latitude=$_POST["latitude"]; 
$longtude=$_POST["longitude"]; 

回報: 說明:未定義指數:緯度在C:\ XAMPP \ htdocs中\的welcome.php第8行

注意:未定義指數:經度 i n C:\ xampp \ htdocs \ welcome.php on line 9

有沒有更好的方法來做到這一點,以及如何解決這個問題?

+1

您使用的getElementById但字段不具有ID – mplungjan

回答

4

您試圖通過ID訪問元素,但他們沒有ID。

可以爲它們添加一個ID屬性,或以不同的方式引用它們。在document.getElementByID

+1

9我的評論和你的答案...... – mplungjan

+0

之間秒我解決這個問題,但仍然是相同的:/ – C0ld

1

你做出錯誤的d要小,即document.getElementById

+1

我看到的部份錯誤,這可能導致錯誤.. – sAnS

+0

您和@ Kolink的答案的組合必須解決這個問題。 – Shomz

0

更改此

function showPosition(position) 
    { 
    var latitude = position.coords.latitude; 
    var longitude = position.coords.longitude; 
    document.getElementByID("longitude").value = longitude; 
    document.getElementByID("latitude").value = latitude; 

    } 

這個

function showPosition(position) 
    { 
    var latitude = position.coords.latitude; 
    var longitude = position.coords.longitude; 
    document.getElementById("longitude").value = longitude; 
    document.getElementById("latitude").value = latitude; 

    } 

,它應該工作

+0

沒有必要複製@ santanu的答案... – Shomz

+0

只是想幫助:) – CuriousMind

0

打開Firebug,點擊標籤網絡,並看看如果參數經度和緯度已發送,則發送請求。如果是的話,失敗必須在你的PHP腳本。如果您找不到這兩個參數,請檢查您的客戶端代碼。