我尝试获取openlayers地图上单击的坐标。我的代码如下:
private long baseId = 0;
ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
@Override
public int getCount() {
return mItems.size();
}
//this is called when notifyDataSetChanged() is called
@Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
@Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
/**
* Notify that the position of a fragment has been changed.
* Create a new ID for each position to force recreation of the fragment
*
* @param n number of items which have been changed
*/
void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
但是我唯一得到的是一个错误:
const localmap = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
function getPosition(event){
console.log(localmap.getEventCoordinate(event));
}
localmap.on('click', getPosition(event));
我尝试将侦听器添加为
Uncaught TypeError: Cannot read property 'changedTouches' of undefined
每次点击都会显示一个数组,但是会用Nan值填充。
我尝试了搜索文档,但所有文档都太旧了,或者直接在侦听器中编写了函数,我不希望这样做,因为我希望能够删除它
有人知道在ol 4.6.5〜5中获得这些坐标吗?
谢谢
答案 0 :(得分:3)
您将需要一个向量数据源,以便在您单击的位置获得诸如像素和坐标之类的位置数据。我已经添加了,尝试包括其他内容,您将得到它。请注意,您将获得的坐标为EPSG:3857
格式,请使用ol.proj.transform()
将其转换为EPSG:4326
。
const localmap = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
source: vectorSource,
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
var vectorSource = new ol.source.Vector({
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
localmap.addLayer(vectorLayer);
localmap.on('singleclick', function (evt) {
console.log(evt.coordinate);
// convert coordinate to EPSG-4326
console.log(ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'));
});
答案 1 :(得分:1)
好吧,原来它只适用于event.coordinate
,并在图层中定义的SRC中显示坐标