2012-04-24 51 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;