最近项目有一个功能需求,在地图上打一个图标图标,可以拖动移动它的位置,获取当前位置座标。直接上代码,提供参考。
要实现这个功能,需要用到 arcgis api 内置的一些鼠标事件,例如:鼠标拖曳(mouse-drag)、鼠标按下(mouse-down)、鼠标放开(mouse-up)。
功能原理:当鼠标按住标注拖动时,触发鼠标拖曳(mouse-drag)事件,实时更新标注的位置座标。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="Stylesheet" type="text/css" href="http://localhost/arcgis_js_api/library/3.18/3.18/esri/css/esri.css" />
<script type="text/javascript">
//下面这段代码必须放到下面几个脚本文件的上面,否则会错误
var dojoConfig = {
api_url: "localhost/arcgis_js_api/library/3.18/3.18",
async : false,
isDebug : true,
parseOnLoad : true,
mblHideAddressBar : false,
packages : [{
name: "lib",
location: location.pathname.replace(/\/[^/]+$/, '') + '/lib'
}]
};
</script>
<script type="text/javascript" src="http://localhost/arcgis_js_api/library/3.18/3.18/init.js"></script>
<script type="text/javascript">
var map, mapCenter;
var selected;
var youtian = "youtianLayer";
var _x, _y, youtianLayer;
require([
"esri/map",
"esri/layers/ArcGISTiledMapServiceLayer",
"esri/layers/GraphicsLayer",
"esri/geometry/Point",
"esri/symbols/SimpleMarkerSymbol",
"esri/symbols/PictureMarkerSymbol",
"esri/InfoTemplate",
"esri/SpatialReference",
"esri/graphic",
"dojo/domReady!"
], function (Map, Tiled, GraphicsLayer, Point, SimpleMarkerSymbol, PictureMarkerSymbol, InfoTemplate, SpatialReference, Graphic) {
map = new Map("map_canvas", {
logo: false,
slider: true
});
//添加基础底图
var basemap = new Tiled("http://192.168.0.196:6080/arcgis/rest/services/GDXJ/DT/MapServer");
map.addLayer(basemap, 0);
youtianLayer = new GraphicsLayer({ id: youtian });
map.addLayer(youtianLayer);
var pms = new PictureMarkerSymbol("../images/RedPin1LargeB.png", 64, 64);
var attr = { "ID": "1", "名称": "地图标注" };
var infoTemplate = new InfoTemplate("企业信息", "企业名称:${ID}<br/>设备故障数:${名称}");
var point1 = new Point(117.12277857421876, 36.632967052981364, new SpatialReference({ wkid: 4326 }));
youtianLayer.add(new Graphic(point1, pms, attr, infoTemplate));
var point = new Point(98.01, 33.80, new SpatialReference({ wkid: 4326 }));
youtianLayer.add(new Graphic(point, pms, attr, infoTemplate));
youtianLayer.on("mouse-down", function (e) {
map.disablePan();
selected = e.graphic;
})
youtianLayer.on("mouse-up", function (e) {
console.log(2);
map.enablePan();
selected = "";
//此处可以写相关的移动标注之后相应的操作,比如保存数据库等
//alert("11");
})
//地图拖动,重新给GraphicsLayer赋值座标位置
map.on("mouse-drag", function (e) {
if (selected) {
var lon = Math.round(e.mapPoint.getLongitude() * 1000) / 1000; //经度
var lat = Math.round(e.mapPoint.getLatitude() * 1000) / 1000; //维度
var pt = new Point(lon, lat, new SpatialReference({ wkid: 4326 })) //GPS使用的是WGS84座标
selected.setGeometry(pt);//给所要移动的图标从新赋值座标
}
})
map.on("mouse-up", function (evt) {
console.log(1);
selected = "";
map.enablePan();
//此处也可以写相关的移动标注之后相应的操作,比如保存数据库等
})
});
</script>
<style type="text/css">
html, body {
margin: 0px;
height: 100%;
}
#map_canvas {
width: 100%;
height: 100%;
margin: 0px auto;
}
</style>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>