如何获取存储在开放层变量中的鼠标坐标?
How to get the mouse coordinates stored in a variable in open layers?
我有一个代码可以在 openlayers 中显示地图外的鼠标位置!
如果我想在调用 js 鼠标事件 onmousedown 和 onmouseup 时保存这些坐标怎么办?
我有以下代码:
const mousePositionControl = new MousePosition({
coordinateFormat: createStringXY(4),
projection: 'EPSG:4326',
className: 'custom-mouse-position',
target: document.getElementById('mouse-position'),
undefinedHTML: ' '
});
const map = new Map({
controls: defaultControls({
attributionOptions: {
collapsible: false
}
}).extend([mousePositionControl]),
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
});
我看到了两种简单的方法。
第一个,只需监听您的 OpenLayers 地图 'click'(或单击)事件。
然后你可以得到光标坐标如下:
myMap.on('click', function(evt){
// Get the pointer coordinate
let coordinate = ol.proj.transform(evt.coordinate);
}
第二个是,每次在地图上移动指针坐标时,使用 'pointermove' 事件,然后在需要时读取它们:
let coord = [];
// We track coordinate change each time the mouse is moved
myMap.on('pointermove', function(evt){
coord = evt.coordinate;
}
// Anytime you want, simply read the tracked coordinate
document.addEventListener('mousedown', function(){
console.log(coord);
});
state={
mouePos:[1,2]
}
this.state.map.on('pointermove', (evt)=>{
this.setState({mousePos:[evt.coordinate[0],evt.coordinate[1]]},()=>{
console.log(evt.coordinate)
})
})
我认为你可以使用 mousePos 状态作为存储
我有一个代码可以在 openlayers 中显示地图外的鼠标位置! 如果我想在调用 js 鼠标事件 onmousedown 和 onmouseup 时保存这些坐标怎么办?
我有以下代码:
const mousePositionControl = new MousePosition({
coordinateFormat: createStringXY(4),
projection: 'EPSG:4326',
className: 'custom-mouse-position',
target: document.getElementById('mouse-position'),
undefinedHTML: ' '
});
const map = new Map({
controls: defaultControls({
attributionOptions: {
collapsible: false
}
}).extend([mousePositionControl]),
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
});
我看到了两种简单的方法。
第一个,只需监听您的 OpenLayers 地图 'click'(或单击)事件。 然后你可以得到光标坐标如下:
myMap.on('click', function(evt){
// Get the pointer coordinate
let coordinate = ol.proj.transform(evt.coordinate);
}
第二个是,每次在地图上移动指针坐标时,使用 'pointermove' 事件,然后在需要时读取它们:
let coord = [];
// We track coordinate change each time the mouse is moved
myMap.on('pointermove', function(evt){
coord = evt.coordinate;
}
// Anytime you want, simply read the tracked coordinate
document.addEventListener('mousedown', function(){
console.log(coord);
});
state={
mouePos:[1,2]
}
this.state.map.on('pointermove', (evt)=>{
this.setState({mousePos:[evt.coordinate[0],evt.coordinate[1]]},()=>{
console.log(evt.coordinate)
})
})
我认为你可以使用 mousePos 状态作为存储