功能:计算某个点到鼠标位置的距离,且移动鼠标,距离跟随变化.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/ol/ol.css" rel="stylesheet" />
<script src="scripts/ol/ol.js"></script>
<script src="scripts/jquery1.9.1.min.js"></script>
<title></title>
<style>
#map {
width: 100%;
height: 700px;
}
</style>
<script>
$(function () {
var raster = new ol.layer.Tile({
source: new ol.source.OSM()//OpenStreetMap
});
var view = new ol.View({
center: new ol.proj.fromLonLat([116.39053344726561, 39.91710957679777]),
zoom: 11
});
var map = new ol.Map({
view: view,
layers: [raster],
target: 'map'
});
//map.on('pointermove', function (e) { //鼠标移动事件,此中方法,无法获取到经纬度
// var lonlat = ol.proj.transform(map.getEventCoordinate(e), 'EPSG:3857', 'EPSG:4326');
// str = "[Map]:" + lonlat;
// document.getElementById("map_xy").innerHTML = str;
//});
//鼠标移动时,计算某点到鼠标所在位置的距离.单位M
//OpenLayers有自带的鼠标移动事件,但是该事件在取经纬度是,获取到的是Nan,所以在这里自己进行注册
$("#map").mousemove(function (e) {
var lonlat = ol.proj.transform(map.getEventCoordinate(e), 'EPSG:3857', 'EPSG:4326');
var wgs84Sphere = new ol.Sphere(6378137);
//到北京的距离
var jl = wgs84Sphere.haversineDistance([116.39053344726561, 39.91710957679777], lonlat);//116.39053344726561, 39.91710957679777
document.getElementById("jl").innerHTML = "距离" + jl;
});
})
</script>
</head>
<body>
<div id="map"></div>
<div id="jl"></div>
</body>
</html>
未完待续...