2012-04-24 53 views
-1

編輯如何完成在<a>標記中的href用JavaScript

我不知道我該怎麼完成從我的JavaScript定位代碼中href。 我有以下功能,它回饋我的經度和緯度。

function(obj){ 
    if(navigator.geolocation){ 
     navigator.geolocation.getCurrentPosition(userPosition,errorPosition); 
    }else { 
     alert('Geolocation is not available'); 
    } 
    function userPosition(position){ 
     obj.setAttribute('href', 'http://maps.google.com/maps? daddr=~ITEM.STREET~,+~ITEM.CITY~&saddr=' + position.coords.latitude + ',' position.coords.longitude); 
    } 
    function errorPosition(error){ 
     switch(error.code){ 
      case eror.PERMISSION_DENIED: 
       alert('permission denied'); 
       break; 
     } 
    } 
} 

在這裏我得到我的當前位置他的經緯度作爲警報。 但我想要做的是以下。目前我有這個。

<a class=localization href="#" onclick="geo(this)"> 
       <img src="images/localizationIcon.png" width=35 height=45 /> 
      </a> 

我想,當我點擊圖像。我的href中填充了經度和緯度。

有人可以幫我嗎?

親切的問候。

燕姿

+0

是那些值會動態改變,而不會擊中服務器? – Mathletics 2012-04-24 13:12:44

+0

不,它們不是 – Steaphann 2012-04-24 13:13:56

回答

1

變化onclick="geo()"onclick="geo(this)"

變化function geo()到​​

代之以userPosition的警告:

obj.setAttribute('href', 'http://maps.google.com/maps? daddr=~ITEM.STREET~,+~ITEM.CITY~&saddr=' + position.coords.latitude + ',' + position.coords.longitude); 

你將不得不調整這符合谷歌地圖格式。我不確定他們想要的地址是什麼,但我很確定你在這種情況下指定了一個街道地址,而不是一個緯度/經度組合。

+0

如果函數是以anchor作爲上下文調用的,則不需要傳遞'this'作爲參數。你可以在你正在使用'obj'的函數內引用'this'。 – Mathletics 2012-04-24 13:18:38

+0

你沒有,但它也沒有傷害。 – 2012-04-24 13:19:40

+0

當然,但它會讓下一位開發人員假設你不瞭解範圍。這就像調用'geo.call(this,this)',這很奇怪。 – Mathletics 2012-04-24 13:24:04

0

我會存儲整個URL和只需更換整個事情。

var url = "google.com/maps?etc"; 
var newval = "google.com/maps?etc&ll"+long+","+lat; 
element.href = newval;