javascript - 当用户使用 javascript 和 openlayers 在网页中单击地图时获取鼠标位置
问题描述
在 openlayers.org 网站上,有一个代码显示了鼠标在地图上的位置。但它不会将位置存储在变量中以供用户使用。当用户单击地图时,我希望有一个代码在窗口中显示用户的位置。请帮我。
我已将提供的代码 openlayers.org 用于显示鼠标的位置。
<!DOCTYPE html>
<html>
<head>
<title>Mouse Position</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<style>
html, body {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
.map {
height: 90%;
width: 100%;
}
</style>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
</head>
<body>
<div id="map" class="map" "></div>
<div id="mouse-position"></div>
<form>
<label>Projection </label>
<select id="projection">
<option value="EPSG:4326">EPSG:4326</option>
<option value="EPSG:3857">EPSG:3857</option>
</select>
<label>Precision </label>
<input id="precision" type="number" min="0" max="12" value="6"/>
</form>
<script>
var mousePositionControl = new ol.control.MousePosition({
coordinateFormat: ol.coordinate.createStringXY(6),
projection: 'EPSG:4326',
// comment the following two lines to have the mouse position
// be placed within the map.
className: 'custom-mouse-position',
target: document.getElementById('mouse-position'),
undefinedHTML: ' '
});
var map = new ol.Map({
controls: ol.control.defaults({
attributionOptions: {
collapsible: false
}
}).extend([mousePositionControl]),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([51.39, 35.70]),
zoom: 13
})
});
var projectionSelect = document.getElementById('projection');
projectionSelect.addEventListener('change', function(event) {
mousePositionControl.setProjection(event.target.value);
});
var precisionInput = document.getElementById('precision');
precisionInput.addEventListener('change', function(event) {
var format = ol.coordinate.createStringXY(event.target.valueAsNumber);
mousePositionControl.setCoordinateFormat(format);
});
</script>
</script>
</body>
</html>
解决方案
推荐阅读
- python - 如何在列表中和列表之间移动特定元素
- prolog - λProlog 拒绝假设的推理查询?
- javascript - 如何使用 vue.js 在所有页面上触发刷新方法
- vb.net - Vb.net 表单的打印部分
- swift - IOS 应用收到 FCM 通知时如何更新表格视图
- r - 使用“glmnet”包进行一步预测 - cv.glmnet
- twilio - Twilio Video JWT 令牌在 api 登录中出错
- javascript - Angular 服务将数据传递给组件
- python - ValueError:操作数无法与形状一起广播 (1202,1) (301,5)
- java - 返回 toString 中的值