如何动态地在图像中添加锚点

时间:2011-05-28 12:52:03

标签: javascript google-maps google-maps-markers

当我们使用Google地图时,在搜索内容后,Google会在地图中添加标记。当我们点击这个标记时,会显示一个详细的信息窗口,如下所示:

enter image description here

我搜索“白宫”,然后创建一个标记“A”。

这并不困难。但是我发现了一些更有趣的东西:

在地图视图中,即使我们不搜索任何东西,当地图缩放到某个指定的级别时,也会产生一些锚点。如果将鼠标悬停在它上面或点击它,它会相应显示,见图像:

enter image description here

这里可以看到“14H和F st NW”。我没有搜索它,但它向我展示了一个锚点。当我点击它时,它会相应地显示一个信息窗口。

但是当我使用Firebug查看正在下载的内容时,我发现它们只是图像。我在HTML中找不到任何<a>标记。

此外,通过Firebug,我发现当地图级别发生变化时,浏览器会向服务器发送请求以获取当前地图视图中的功能。响应是JSON格式。它包含要素的位置和名称,然后在地图中添加锚点。

但我想知道他们是如何实现的?

<小时/> <小时/> 实现这个的可能方式:

1)当地图缩放或平移时,从服务器请求要素位置数据,假设他们得到以下数据(例如以白宫为例):

数据:{{名称:'白宫',纬度:-77经度:38}}

2)将鼠标悬停在地图div上,如下所示:

$("#map").mousemove(function(e){
 for(var i=0;i<data.length;i++){
   if(e.clientX=getImageX(data[i].x) && e.clientY=getImageY(data[i].y)){
     //it mean that the mouse is overing this feature,now set the cousor and show the tip
     //show tip,see the iamge:
   }
 }

});

enter image description here

3)将click事件绑定到map div“

$("#map").mousemove(function(e){
 for(var i=0;i<data.length;i++){
   if(e.clientX=getImageX(data[i].x) && e.clientY=getImageY(data[i].y)){
     //it mean that the mouse is clicking this feature,show the infomation window
     //show tip,see the iamge:
   }
 }

});

以上就是我现在所能想到的。但似乎还不够,还有一些问题:

1)提示信息窗口只能显示用户点击或鼠标悬停在与该功能的纬度和经度相同的点上,但在谷歌地图中,​​您会发现如果鼠标悬停在标记(在标记的任何一点),尖端将显示。引起尖端显示的区域与标记的区域相同。

似乎google做了这样的事情:

$("#map").mousemove(function(e){
 for(var i=0;i<data.length;i++){
   if(e.clientX.insideTheMarker(data[i]) && e.clientY=insideTheMarker(data[i])){

     //it mean that the mouse is clicking this feature,show the infomation window
   }
 }
});

但是游行规模并不相同,他们如何计算将使小费显示的真实区域?

2)在eventhandle函数中,我需要迭代所有的功能,看看当前鼠标的位置是否与任何功能匹配,如果当前地图视图中的功能太多,那么它必然会导致性能问题。

1 个答案:

答案 0 :(得分:2)

图像或地图div可能是onclick事件。您可以在任何DOM元素上放置onclick处理程序。在这种情况下,他们可能如果他们将事件放在地图div上,因为很可能会有很多图像会有事件,这可能是性能问题。

当您处理父元素中的子元素的click事件时,它被称为事件委派。 jQuery提供了2个用于执行事件委派.live.delegate的函数。其他库也提供此功能,但您可以阅读此general javascript turorial或此jQuery specific tutorial的基础知识。

他们可能正在做类似的事情(从here修改):

// Get the map canvas  
var mapcanvas = document.getElementById('map_canvas');  

// Quick and simple cross-browser event handler - to compensate for IE's attachEvent handler  
function addEvent(obj, evt, fn, capture) {  
    if ( window.attachEvent ) {  
        obj.attachEvent("on" + evt, fn);  
    }  
    else {  
        if ( !capture ) capture = false; // capture  
        obj.addEventListener(evt, fn, capture)  
    }  
}  

// Check to see if the node that was clicked is an anchor tag. If so, proceed per usual.  
addEvent(mapcanvas, "click", function(e) {  
  // Firefox and IE access the target element different. e.target, and event.srcElement, respectively.  
  var target = e ? e.target : window.event.srcElement;  
  if ( target.nodeName.toLowerCase() === 'img' ) {  
     alert("clicked");  
     return false;  
  }  
}); 

至于使图像看起来像锚(即指针鼠标图标),可以通过设置光标属性来设置css:

#map_canvas img { cursor: pointer }
相关问题