【问题标题】:get coördinates as variables from openlayer 3 map从 openlayer 3 地图中获取坐标作为变量
【发布时间】:2016-04-19 13:09:18
【问题描述】:

对于我的项目,每当我点击地图时,我想用 x 和 y 坐标填充一个文本框。我用这个标准代码在我的屏幕上显示了坐标:

var mousePositionControl = new ol.control.MousePosition({
    className: 'custom-mouse-position',
    target: document.getElementById('location'),
    coordinateFormat: ol.coordinate.createStringXY(5),
    undefinedHTML: ' '
  });

所以我想:如果我使用 mousePositionControl 作为 x 和 y 坐标的变量,我会在文本框中得到它。所以我尝试了这个:

map.on('click', function() {
document.getElementById("coördinates").value = mousePositionControl;
});

但我在文本框中得到的结果是:[object Object]

有人可以帮我解决这个问题吗?

【问题讨论】:

  • ol.control.MousePosition 类型对象的字符串表示形式是“[object Object]”,因此代码完全按照您的要求执行。 click 处理程序接收 event 对象,该对象已包含单击像素的坐标,因此无需涉及控件。
  • 是元素location,显示xy。为什么元素coördinates需要第二次获取xy
  • 附带说明,“coördinates”和“coöperate”在英文中分别写为“coordinates”和“cooperate”。

标签: openlayers-3


【解决方案1】:
map.on('click', function(evt){
    document.getElementById('coördinates').innerHTML = evt.coordinate.join(", ");
});

【讨论】:

  • 一些关于为什么这可以解决问题的评论将使这个问题成为一个更好的答案
【解决方案2】:

我只是自己想出来的。我要了完整的元素,然后条纹并替换了它,所以我得到了我得到的东西。

代码:

map.on('click', function() {
  var show = document.getElementById("location").innerHTML;
  var clean = show.replace('<div class="custom-mouse-position">', "");
  var clean_again = clean.replace('</div>', "");
  var split = clean_again.split(',');
});

【讨论】:

  • 您不应该将 html 代码作为字符串处理;它不干净,在某些浏览器或未来版本中可能会失败。建议改为使用 DOM 来选择您需要的元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多