谷歌地球API,如何防止重复的标记

Google Earth API, how to prevent duplication of placemarks?

本文关键字:何防止 API 谷歌地球      更新时间:2023-09-26

我已经可以在点击时创建占位符了!我想要的是防止用户创建另一个具有相同lat和long值的占位符。这是我基于GoogleEarthApi的初始代码。

不知怎么的,它似乎不起作用。。。如何确保用户不会在同一纬度上创建新的占位符?

我认为if (event.getTarget().getType() != 'KmlPlacemark' && event.getTarget().getGeometry().getType() != 'KmlPoint'应该发挥作用。。知道吗?T_T

google.earth.addEventListener(ge.getGlobe(), 'click', function(event) {
    if (event.getTarget().getType() != 'KmlPlacemark' &&
          event.getTarget().getGeometry().getType() != 'KmlPoint') {
                      event.preventDefault();
                      //create a place marker for the pole
                    var poleMarker = ge.createPlacemark('');
                    var point = ge.createPoint('');
                    point.setLatitude(event.getLatitude());
                    point.setLongitude(event.getLongitude());
                    poleMarker.setGeometry(point);
                    ge.getFeatures().appendChild(poleMarker);
                    }
                  });

匿名函数的逻辑有点多余。让我解释一下。

首先,您指定侦听目标"GEGlobe"对象上的"点击"事件。

google.earth.addEventListener(ge.getGlobe(), 'click', ...

然后,在条件语句中,您将测试事件的目标,即"GEGlobe"对象,是否不是KmlPlacemark或KmlPoint-但这始终是真的。这是因为事件传播的工作方式。事件总是会传播到GEGlobe,因此情况总是真实的。

if (event.getTarget().getType() != 'KmlPlacemark' &&
          event.getTarget().getGeometry().getType() != 'KmlPoint') ...

您可以查看event.stopPropagationevent.preventDefault,但对于您的情况,一个简单的解决方案"…防止用户创建另一个具有相同lat和long值的占位符…"是存储lat-lng值,如果值已经存储,则不创建占位符。例如,以下内容可能适用于您。显然,还有其他方法可以做到这一点,但无论你实际编码如何,存储位置并检查它们的原则都是正确的

// to hold the places clicked
var locations = new Array();
google.earth.addEventListener(ge.getGlobe(), 'click', function(event)
{
  event.preventDefault();
  // create a string of the place
  var place = event.getLatitude() + ',' + event.getLongitude();
  // if the place is not the locations array
  if(locations.indexOf(place) == -1)
  {
    // add the place to the locations array
    locations.push(place);
    // create a place marker for the pole
    var poleMarker = ge.createPlacemark('');
    var point = ge.createPoint('');
    point.setLatitude(event.getLatitude());
    point.setLongitude(event.getLongitude());
    poleMarker.setGeometry(point);
    ge.getFeatures().appendChild(poleMarker);
  }  
});