繁体   English   中英

Google Earth插件-如何检查具有ID的元素是否已经存在?

[英]Google Earth plugin — how to check if an element with an ID already exists?

我通过以下方式创建和分配样式(例如C#):

// ge — IGEPlugin instance
var placemark1 = ge.createPlacemark("placemark1");
var style1 = ge.createStyle("style1");
style1.getLineStyle().setWidth(2);
placemark1.setStyleSelector(style1);
// ... add placemark to ge features...

如何检查GE中是否已存在ID为style1的元素? 如果我调用ge.createPlacemark("placemark1") ,则第二次执行此操作会收到COM错误。

我无法使用ge.getElementById("style1")获得元素-它始终返回null。

有两件事,首先是一个访问器getComputedStyle ,它使您可以将对象样式属性作为KMLStyle对象获取。

dynamic placemarkStyle = placemark1.getComputedStyle();
string id = placemarkStyle.getId();

也许您可以根据需要使用此方法来引用样式对象...

您还可以通过将类型名称作为字符串传递给getElementsByType来获得某个类型的所有元素的数组。 这样的事情应该可以工作(尽管未经测试...)

public bool DoesStyleExist(string id)
{
  var styles = ge.getElementsByType('style');
  int l = styles.getLength();

  if(l == 0) 
  {
    // no styles
    return false;
  }

  for (var i = 0; i < l; ++i) {
    var style = style.item(i);
    var styleid = style.getId();
    if(id == styleid)
    {
      // matching style id
      return true;
    }
  }

  // no match
  return false;
}

编辑

根据您的评论,您的代码中一定存在错误-我已经测试了以下内容,并且可以正常工作。

  // create the placemark
  placemark = ge.createPlacemark('pm1');
  var point = ge.createPoint('');
  point.setLatitude(37);
  point.setLongitude(-122);
  placemark.setGeometry(point);

  // add the placemark to the earth DOM
  ge.getFeatures().appendChild(placemark);

  var styleMap = ge.createStyleMap('');

  // Create normal style for style map
  var normalStyle = ge.createStyle('style1');
  var normalIcon = ge.createIcon('icon1');
  normalIcon.setHref('http://maps.google.com/mapfiles/kml/shapes/triangle.png');
  normalStyle.getIconStyle().setIcon(normalIcon);

  // Create highlight style for style map
  var highlightStyle = ge.createStyle('style2');
  var highlightIcon = ge.createIcon('icon2');
  highlightIcon.setHref('http://maps.google.com/mapfiles/kml/shapes/square.png');
  highlightStyle.getIconStyle().setIcon(highlightIcon);

  styleMap.setNormalStyle(normalStyle);
  styleMap.setHighlightStyle(highlightStyle);

  // Apply stylemap to a placemark
  placemark.setStyleSelector(styleMap);

  alert(ge.getElementById('pm1')); // object 
  alert(ge.getElementById('style1')); // object 
  alert(ge.getElementById('style2')); // object

  DoesStyleExist('style1'); // true
  DoesStyleExist('style2'); // true
  DoesStyleExist('foo'); // false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM