2013-08-23 66 views
0
function getMyLocation() { 
if(navigator.geolocation){ 
    navigator.geolocation.getCurrentPosition(displayLocation); 
} 
else{ 
    alert("Geolocation not supported"); 
} 
} 

var user_lat; 
var user_long; 
var d_long; 
var d_lat; 

function displayLocation(position) { 
user_lat = position.coords.latitude; 
user_long = position.coords.longitude; 
alert("you are at lat: " + user_lat + " ,longitude: " + user_long); 
} 

function getLocationDestination() { 
var e = document.getElementById("building"); 
var strUser = e.options[e.selectedIndex].text; 

alert("you want to go to " + strUser + " and the cords are " + building_array[strUser]); 

getMyLocation(); 
alert("heelo"); 
displayLocation(position); 
alert("heelo"); 
displayLocation(position); 
} 

該代碼非常簡單,但是當我運行geoLocationDestination()時,我沒有從displayLocation(position)得到第二個警報,即使在運行它的while循環中也沒有發生20次。該程序在第二次打招呼後退出?有任何想法嗎?Javascript HTML5地理位置錯誤?

+0

看起來'position'在'getLocationDestination()'中是未定義的...... – Passerby

回答

0

當我運行代碼,我得到的位置是在displaylocation功能定義,這是因爲你需要調用從getMyLocation此功能,而不是seperately通過位置參數,下面 是一個工作代碼,

<html> 
<script> 
function getMyLocation() { 
if(navigator.geolocation){ 
navigator.geolocation.getCurrentPosition(displayLocation); 
} 
else{ 
alert("Geolocation not supported"); 
} 
} 

var user_lat; 
var user_long; 
var d_long; 
var d_lat; 

function displayLocation(position) { 


user_lat = position.coords.latitude; 
user_long = position.coords.longitude; 
alert("you are at lat: " + user_lat + " ,longitude: " + user_long); 
} 

function getLocationDestination() { 
var sel = document.getElementById("foo"); 
var option = sel.options[sel.selectedIndex]; 
var text = option.text; 
var value = option.value; 
alert(text, value); 

getMyLocation(); 

} 

</script> 
<input type="submit" id=hello onclick=getLocationDestination();> 
<select id="foo"> 
<option value="1">One</option> 
<option value="2">Two</option> 
<option value="3">Three</option> 
</select> 

</html> 

此代碼顯示選擇框中的選定值並給出警報(我假設它是「你想要去的」部分編碼,我不確定這是否因爲你沒有包含HTML部分),然後 提醒經緯度