1

我正在尝试使用以下代码将鼠标事件附加到 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"); 
                    });

但是单击没有显示任何结果。任何想法为什么?

谢谢!账单

4

3 回答 3

1

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

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

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

出于某种原因,事件只是不会触发。这里有一个错误报告(我相信覆盖问题已合并到其中......) https://code.google.com/p/earth-api-samples/issues/detail?id=123

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

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

// 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
};

我在这里做了一个工作示例。

于 2013-07-27T16:00:32.740 回答
1

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

它在自己的结构中维护有关叠加层的信息(而不是遍历 KML,这可能是可能的)。

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

一旦知道顶点,在鼠标移动上运行的命中测试基于如何确定 2D 点是否在多边形内?

因此,此代码说明了以下方面的起始想法:

  • 如何从叠加层合成鼠标事件(一种解决方法,直到 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>
于 2013-07-30T16:00:28.150 回答
0

你正试图做太多太快。首先,您需要将事件监听器添加到 GE Plugin

所以更换

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>高于Polygon的 a<drawOrder>的数字GroundOverlay

希望这有效!

于 2012-10-18T17:38:06.907 回答