arcgis.js中有 toMap(),toScreen()两个方法。
toMap()是将一个浏览器坐标(x,y)转换成地图坐标(经纬度)
toScreen()是将地图上的坐标转换成浏览器中的坐标
注意是浏览器中的坐标
toScreen()方法的使用重点就是我们需要先将点point添加到view容器中,再从中取出来,进行转换,否则会出现undefined的结果,这与地图中的一些设置有关。
下面上代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>toMap()&toScreen()</title>
<style>
html,
body {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
#viewDiv {
height: 60%;
width: 40%;
}
</style>
<!-- 导入arcgis -->
<link rel="stylesheet" href="https://js.arcgis.com/4.22/esri/themes/light/main.css" />
<script src="https://js.arcgis.com/4.22/"></script>
</head>
<body>
<div id="viewDiv" style="border: 1px red solid;"></div>
<div id="location" style="position: absolute;z-index: 1;background:red;">
1231234
</div>
<script>
console.log("view.toMap(),view.toScreen()方法使用")
//使用arcgis.js
require([
"esri/Map",
"esri/views/MapView",
"esri/Graphic",
],
(Map, MapView, Graphic) => {
let centerPoint = [116, 39];
//底层
const map = new Map({
basemap: "osm"
});
const view = new MapView({
container: "viewDiv",
map: map,
zoom: 15,
center: [116, 39]
});
let point = {
type: "point",
longitude: 116,
latitude: 39,
// spatialReference: {
// wkid: 4326
// }
};
let pointSymbol = {
type: "simple-marker",
color: [255, 0, 0],
style: "circle",
size: 10,
};
let pointGraphic = new Graphic({
geometry: point,
symbol: pointSymbol
});
view.graphics.add(pointGraphic);
//要在view加载完毕后调用toScreen和toMap,否则就是null
view.watch("extent", function(evt) {
let item = view.graphics.getItemAt(0);
//地图上的经纬度 >> 转成 >>屏幕上的坐标点
console.log("item.geometry:", item.geometry)
let screenPoint = view.toScreen(item.geometry);
console.log("toScreen:", screenPoint)
let domDiv = document.getElementById("location");
domDiv.style.top = Number(screenPoint.y) + "px";
domDiv.style.left = Number(screenPoint.x) + "px";
//屏幕上的坐标点 >>转成>> 地图上的经纬度
let testPoint = {
x: 384,
y: 200.5
};
let mapPoint = view.toMap(testPoint);
console.log("toMap:", mapPoint)
})
})
</script>
</body>
</html>