将事件附加到Google地球插件API中的groundOverlay

时间:2012-10-18 14:08:40

标签: javascript google-earth-plugin

我正在尝试使用以下代码将鼠标事件附加到groundOverlay功能:

     var groundOverlay = ge.createGroundOverlay('');
        var icon = ge.createIcon('');
        icon.setHref("http://www.google.com/logos/earthday08.gif");
        groundOverlay.setIcon(icon);
        var latLonBox = ge.createLatLonBox('');
        latLonBox.setBox(48.80, 48.75, -121.77, -121.85, 0);
        groundOverlay.setLatLonBox(latLonBox);
        ge.getFeatures().appendChild(groundOverlay);    

          google.earth.addEventListener(groundOverlay, 'click', function(e) { 
                    e.preventDefault();
                    console.log("hello"); 
                    });

但点击显示没有结果。有什么想法吗?

谢谢! 比尔

3 个答案:

答案 0 :(得分:1)

这是一个错误,您发布的代码完全正确。

KmlGroundOverlay对象确实从GEEventEmitter继承,因此它具有标准KmlMouseEvents; mousedown,mouseup,mousemove等。

你可以在这里清楚地看到:https://developers.google.com/earth/documentation/reference/interface_kml_ground_overlay-members

由于某种原因,这些事件不会发生。这里有一个错误报告(Overlay问题合并到它我相信......) https://code.google.com/p/earth-api-samples/issues/detail?id=123

正如@lifeIsGood所说,在他的回答中,最好的解决方法是在GroundOverlay下放置一个具有相同几何形状的透明多边形。但是,至少以编程方式将不透明度设置为0并不是一个好主意。 Opacity is experimental目前,如果您将某个对象设置为0,那么KmlMouseEvents通常不会为该对象触发。我相信插件在完全透明时会有效地从事件链中删除该功能。无论如何,为了防止这种情况,将不透明度设置为.1而不是0

处理多边形上事件的更好方法是将GroundOverlay传递回处理程序。这样,当引发事件时,您可以在处理程序中引用GroundOverlay和事件数据,而无需任何全局变量或唯一ID。 e.g。

// attach the event to the transparent polygon discussed
google.earth.addEventListener(polygon, 'click', function(e) {
  handler(overlay, e)
});

// handle the event.
// sender is the overlay
// event is the real KmlMouseEvent from the polygon.
function handler(sender, event) {
  console.log(sender.getType());  //KmlGroundOverlay
  console.log(event.getTarget().getType());  //KmlPolygon
};

I made a working example of this here.

答案 1 :(得分:1)

由于KmlGroundOverlays尚未生成鼠标事件,另一种解决方法是从地球接收鼠标事件,然后确定鼠标是否在叠加层内(“命中测试”)。下面是使用mouseMove事件执行此操作的代码的起点。它生成两个重叠的叠加层(一个旋转)并将鼠标下的叠加层带到表面(通过操纵drawingOrder)。

它维护有关其自身结构中叠加层的信息(而不是走KML,这可能是可能的)。

我无法找到从GE获取旋转叠加层顶点位置的方法,因此使用笛卡尔近似法在代码中完成旋转。此代码可能会在极点或边界或大多边形上断开。

一旦知道顶点,在鼠标移动时运行的命中测试基于How can I determine whether a 2D Point is within a Polygon?

上的精彩讨论

所以这段代码说明了:

的启动思路
  • 如何从叠加层合成鼠标事件(解决方案直到KML叠加层可以生成鼠标事件)
  • 如何近似旋转叠加层的顶点(以找到叠加层的位置)
  • 对叠加层进行命中测试(来自上述参考文献)
  • 使用drawOrder在鼠标悬停时将重叠的叠加层添加到表面

http://jsfiddle.net/pudkg/

有一个演示

这是代码& HTML:

<!DOCTYPE html>

<html>
<head>

<script type="text/javascript" src="https://www.google.com/jsapi"> </script>

<script type="text/javascript">
var ge;
var overlays = [];   // record information about overlays (filled by 'addOverlay')
var drawOrder = 0;   // drawOrder value of topmost overlay
google.load("earth", "1");

function Point (lat, lon) {
  this.lat = lat;
  this.lon = lon;
}

function Overlay (groundOverlay, points, drawOrder) {
  this.overlay = groundOverlay;  // KML object
  this.points = points;          // array of Points (vertices of overlay)
  this.drawOrder = drawOrder;    // integer, higest displayed topmost
}
Overlay.prototype.hitTest = function (lat, lon) {   // return true if lat/lon is within overlay
    // Based upon https://stackoverflow.com/questions/217578/point-in-polygon-aka-hit-test
    var isInside = false;
    var minLon = this.points[0].lon, maxLon = this.points[0].lon;
    var minLat = this.points[0].lat, maxLat = this.points[0].lat;
    for (var n = 1; n < this.points.length; n++) {
      var q = this.points[n];
      minLon = Math.min(q.lon, minLon);
      maxLon = Math.max(q.lon, maxLon);
      minLat = Math.min(q.lat, minLat);
      maxLat = Math.max(q.lat, maxLat);
    }
    if (lon < minLon || lon > maxLon || lat < minLat || lat > maxLat)
      return false;

    var i = 0, j = this.points.length - 1;
    for (i, j; i < this.points.length; j = i++)
      if ( (this.points[i].lat > lat) != (this.points[j].lat > lat) &&
          lon < (this.points[j].lon - this.points[i].lon) * (lat - this.points[i].lat) /
          (this.points[j].lat - this.points[i].lat) + this.points[i].lon )
        isInside = !isInside;
    return isInside;
  }

function init() {
  google.earth.createInstance('map3d', initCB, failureCB);
}

function initCB(e) {
  ge = e;
  ge.getWindow().setVisibility(true);

  var lat = 37.204193;
  var lon = -112.934429;
  var dlat = 0.003;
  var dlon = 0.005;
  var offset = 0.004;

  var la = ge.createLookAt('');  // position camera
  la.set(lat, lon, 0, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 30, 2000);
  ge.getView().setAbstractView(la);

  for (var i = 0; i < 2; i++)  // generate two overlays, overlapping; second one rotated
    addOverlay('http://www.google.com/logos/earthday08.gif',
        lat + dlat + offset*i, lat - dlat + offset*i,
        lon + dlon + offset*i, lon - dlon + offset*i, 30*i);
  // KML overlays can't (yet) generate mouse events, so look for events from globe
  google.earth.addEventListener(ge.getGlobe(), 'mousemove', function(event) {
    var lat = event.getLatitude();
    var lon = event.getLongitude();
    // show that a move event was received:
    document.getElementById('logMove').innerHTML = event.getLatitude();
    topmost = -1, zMax = 0;  // find topmost overlay
    for (var i = overlays.length - 1; i >= 0; i--)
      if (overlays[i].hitTest(lat, lon)) {  // if mouse is within overlays[i]
        document.getElementById('logHit').innerHTML = i + '; ' + overlays[i].drawOrder;
        if (overlays[i].drawOrder > zMax) {  // if this overlay is higher than any previous
          topmost = i;
          zMax = overlays[i].drawOrder;
        }
      }
    if ((topmost >= 0) && (overlays[topmost].drawOrder < drawOrder)) {
      // if in an overlay and it is buried, make it top-most
      overlays[topmost].overlay.setDrawOrder(++drawOrder);
      overlays[topmost].drawOrder = drawOrder;  // update local structure
    }
    document.getElementById('logOver').innerHTML = topmost + '; ' + zMax;
  });
}

function addOverlay(url, north, south, east, west, rotation) {
  var groundOverlay = ge.createGroundOverlay('');  // create overlay
  var icon = ge.createIcon('');
  icon.setHref(url);
  groundOverlay.setIcon(icon);
  var latLonBox = ge.createLatLonBox('');
  latLonBox.setBox(north, south, east, west, rotation);
  groundOverlay.setLatLonBox(latLonBox);
  groundOverlay.setDrawOrder(++drawOrder);
  ge.getFeatures().appendChild(groundOverlay);
  var points = [];  // figure out lat/lon of the corners of the overlay
  var sinTheta = Math.sin(rotation * Math.PI / 180.0);
  var cosTheta = Math.cos(rotation * Math.PI / 180.0);
  // rotation is about the center of the overlay; find midpoint:
  var midPoint = new Point((north + south) / 2, (west + east) / 2);
  // To do cartesian rotation, need to consider that the distance between
  // units of longitude diminish as one goes north, to zero at pole:
  var cosLat = Math.cos(midPoint.lat * Math.PI / 180.0);  // longitude compression factor
  west = (west - midPoint.lon) * cosLat, east = (east - midPoint.lon) * cosLat;
  north -= midPoint.lat, south -= midPoint.lat;
  // use cartesian rotation (good enough approximation for UI away from pole, boundaries)
  // after rotation, restore (expand) longitudes by compression factor
  points.push(new Point(midPoint.lat + west * sinTheta + north * cosTheta,
      midPoint.lon + (west * cosTheta - north * sinTheta) / cosLat));
  points.push(new Point(midPoint.lat + east * sinTheta + north * cosTheta,
      midPoint.lon + (east * cosTheta - north * sinTheta) / cosLat));
  points.push(new Point(midPoint.lat + east * sinTheta + south * cosTheta,
      midPoint.lon + (east * cosTheta - south * sinTheta) / cosLat));
  points.push(new Point(midPoint.lat + west * sinTheta + south * cosTheta,
      midPoint.lon + (west * cosTheta - south * sinTheta) / cosLat));
  overlays.push(new Overlay(groundOverlay, points, drawOrder));
}

function failureCB(errorCode) {
  alert("GE init fail");
}

google.setOnLoadCallback(init);
</script>
</head>

<body>

<div id=map3d style='height: 400px; width: 600px'></div>
<p>Mouse over the two overlays.  The one under the mouse should come to surface.</p>
<p>Latitude of mouse: <span id=logMove></span></p>
<p>Index of last overlay hit; its drawOrder: <span id=logHit></span></p>
<p>Index of topmost overlay; max drawOrder: <span id=logOver></span></p>

</body>
</html>

答案 2 :(得分:0)

你想要太快做太多。 首先,您需要将事件侦听器添加到GE插件

所以替换

google.earth.addEventListener(groundOverlay, 'click', function(e) {

google.earth.addEventListener(ge.getGlobe(), 'click', function(e) {

根据您正在做的事情,有时最好使用ge.getWindow()ge.getView()

编辑:评论指出错误后

不是检测GroundOverlay上的点击,而是创建覆盖完全相同地形的Polygon,然后检测点击它。

创建Polygon时,我会将其设为'隐形',但将不透明度设置为零。然后在我之前的回答中,在确定是否单击时使用unique_id

将unique_id设置为多边形:在KML中它看起来像这样

<Placemark id="unique_id">
<name>Polygon Name</name>
<styleUrl>....</styleUrl>
<Polygon>
  .....
</Polygon>
</Placemark>

然后在eventListener

中使用这种函数
    var obj = e.getTarget();
         if (obj.getType() == 'KmlPlacemark') {
         e.preventDefault();
         var placemark = obj;
         var placemark_id = placemark.getId();
              if (placemark_id == 'unique_id') {
              console.log("hello");
              }
    }

我知道您可以通过这种方式检测到Polygon上的点击,因此这个想法适用于GroundOverlays。我没有测试过它。如果您遇到问题,我建议您将<drawOrder>的{​​{1}}设置为高于Polygon的{​​{1}}

的数字

希望这有效!