高德地图 JS API 常用技巧
2020/04
09
12:04
自定义地图
指定Map.mapStyle
属性,实现自定义样式地图。
var map = new AMap.Map('container', { resizeEnable: true, zoom:4, center: [116.397428, 39.90923], mapStyle:'amap://styles/a92c23c68ca519ec235825c3be99462b' //前往创建自定义地图样式:https://lbs.amap.com/dev/mapstyle/index });
使用Map.setMapStyle()
方法,加载高德提供的模版样式。
map.setMapStyle("amap://styles/normal");
地图显示要素
使用Map.setFeatures()
方法,定制地图显示的元素类别。
var map = new AMap.Map('container', { resizeEnable: true, //是否监控地图容器尺寸变化 zoom: 17, center: [116.408075, 39.950187], features: ['bg', 'road', 'building', 'point'] // bg区域面 road道路 building建筑物 point标注 }); map.setFeatures(myFeatures);
隐藏文字标注
showLabel
设定为 false
隐藏文字标注。
//初始化地图 var map = new AMap.Map('container', { resizeEnable: true, //是否监控地图容器尺寸变化 showLabel: false //不显示地图文字标记 });
3D地图
var map = new AMap.Map('container', { resizeEnable: true, // 地图容器尺寸变化 rotateEnable:true, // 旋转 写为false将固定视角无法旋转 pitchEnable:true, // 倾斜 写为false将固定时间无法倾斜 zoom: 17, pitch:80, rotation:-15, viewMode:'3D',//开启3D视图,默认为关闭 buildingAnimation:true,//楼块出现是否带动画 expandZoomRange:true, zooms:[3,20], center:[116.333926,39.997245] }); // 添加控件按钮 控制旋转 倾斜角度 map.addControl(new AMap.ControlBar({ showZoomBar:false, // 是否显示缩放按钮 showControlButton:true, // 是否显示控制旋转 倾斜角度按钮 position:{ right:'10px', top:'10px' } // 控件显示的位置 }))
坐标系转换
使用 lnglatTocontainer()
和 containTolnglat()
将经纬度坐标与地图容器像素坐标相互转换
var pixel = new AMap.Pixel(x,y); // 参数为x,y 容器像素坐标 var lnglat = map.containerToLngLat(pixel); // 得到转换的经纬度 var lnglat = new AMap.LngLat(lng, lat);// 参数为经度,纬度 var pixel = map.lnglatTocontainer(lnglat); // 得到转换的容器像素坐标 var lnglat = new AMap.LngLat(lng, lat);// 参数为经度,纬度 var pixel = map.lnglatToPixel(lnglat,zoom); // 参数为经纬度和缩放层级。得到转换的平面坐标 pixel.x = parseInt(pixel.x); // 取整 pixel.y = parseInt(pixel.y); var pixel = new AMap.Pixel(x,y); // 参数为平面坐标x,y var lnglat = map.pixelToLngLat(pixel,zoom); // 参数为平面坐标和缩放层级 得到转换的经纬度 // 经纬度转换为三维坐标 var lnglat = new AMap.LngLat(lng, lat); var pixel = map.lngLatToGeodeticCoord(lnglat); pixel.x = parseInt(pixel.x); pixel.y = parseInt(pixel.y); // 三维坐标转换为经纬度 var pixel = new AMap.Pixel(x,y); var lnglat = map.geodeticCoordToLngLat(pixel);
事件
- 地图加载完成事件:
map.on('complete', function() {})
- 地图移动相关事件
map.on('movestart', mapMovestart);
:移动开始map.on('mapmove', mapMove);
: 移动中map.on('moveend', mapMoveend);
: 移动结束map.off('movestart', mapMovestart);
:off移除事件map.off('mapmove', mapMove);
map.off('moveend', mapMoveend);
- 地图缩放相关事件
map.on('zoomstart', mapZoomstart);
: 缩放开始map.on('zoomchange', mapZoom);
:缩放等级改变map.on('zoomend', mapZoomend);
:缩放结束map.off('zoomstart', mapZoomstart);
map.off('zoomchange', mapZoom);
map.off('zoomend', mapZoomend);
- 地图点击和鼠标事件
map.on('dblclick', showInfoDbClick);
:双击map.on('click', showInfoClick);
:单击map.on('mousemove', showInfoMove);
:移动map.off('click', showInfoClick);
map.off('dblclick', showInfoDbClick);
map.off('mousemove', showInfoMove);
- 地图拖拽相关事件
map.on('dragstart', showInfoDragstart);
:拖拽开始map.on('dragging', showInfoDragging);
:拖拽中map.on('dragend', showInfoDragend);
:拖拽结束map.off('dragstart', showInfoDragstart);
map.off('dragging', showInfoDragging);
map.off('dragend', showInfoDragend);
- 覆盖物点击和鼠标事件
var map = new AMap.Map("container", { resizeEnable: true }); var marker = new AMap.Marker({ map: map, icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", position: [116.405467, 39.907761] }); var lnglat =[116.368904, 39.913423]; var circle = new AMap.Circle({ map: map, center: lnglat , //设置圆心 radius: 1500, strokeColor: "#3366FF", //边框线颜色 strokeOpacity: 0.3, //边框线透明度 strokeWeight: 3, //边框线宽 fillColor: "#FFA500", //填充色 fillOpacity: 0.35//填充透明度 }); var polygonArr = [[116.403322, 39.920255], [116.410703, 39.897555], [116.402292, 39.892353], [116.389846, 39.891365]]; var polygon = new AMap.Polygon({ map: map, path: polygonArr,//设置多边形边界路径 strokeColor: "#FF33FF", //线颜色 strokeOpacity: 0.2, //线透明度 strokeWeight: 3, //线宽 fillColor: "#1791fc", //填充色 fillOpacity: 0.35//填充透明度 }); map.setFitView(); // 注册 marker.on('click', showInfoM); circle.on('click', showInfoC); polygon.on('click', showInfoP); marker.on('mouseover', showInfoOver); circle.on('mouseover', showInfoOver); polygon.on('mouseover', showInfoOver); marker.on('mouseout', showInfoOut); circle.on('mouseout', showInfoOut); polygon.on('mouseout', showInfoOut); // 解除 marker.off('click', showInfoM); circle.off('click', showInfoC); polygon.off('click', showInfoP); marker.off('mouseover', showInfoOver); circle.off('mouseover', showInfoOver); polygon.off('mouseover', showInfoOver); marker.off('mouseout', showInfoOut); circle.off('mouseout', showInfoOut);
- 覆盖物拖拽事件
需要在初始化的时候添加属性draggable: true
marker.on('dragging', showInfoM); circle.on('dragging', showInfoC); polygon.on('dragging', showInfoP); marker.off('dragging', showInfoM); circle.off('dragging', showInfoC); polygon.off('dragging', showInfoP);
- 信息窗体打开关闭事件
var info = []; info.push("<div><div><img style=\"float:left;\" src=\" https://webapi.amap.com/images/autonavi.png \"/></div> "); info.push("<div style=\"padding:0px 0px 0px 4px;\"><b>高德软件</b>"); info.push("电话 : 010-84107000 邮编 : 100102"); info.push("地址 :北京市朝阳区望京阜荣街10号首开广场4层</div></div>"); infoWindow = new AMap.InfoWindow({ content: info.join("<br/>") //使用默认信息窗体框样式,显示信息内容 }); infoWindow.open(map, map.getCenter()); // 打开信息窗体 infoWindow.close(); // 关闭信息窗体 infoWindow.on('open',showInfoOpen) // 监听信息窗体打开事件 infoWindow.on('close',showInfoClose) // 监听信息窗体关闭事件
- DOM事件
var button1 = document.getElementById('bt1'); AMap.event.addDomListener(button1, 'click', handle);//给div绑定单击事件 var clickListener; function handle() { remove(); //防止重复绑定 clickListener = AMap.event.addListener(map, "click", function(e) { // 注意这里是给地图绑定事件 new AMap.Marker({ position: e.lnglat, map: map });// 鼠标点击哪在哪生成标记 }); }; function remove() { if (clickListener) { AMap.event.removeListener(clickListener);//移除事件,以绑定时返回的对象作为参数 } };
- 自定义事件
map.on("myEvents", fn); //绑定自定义事件,返回监听对象 var fn = function(e) { console.log(e.msg) } map.emit('myEvents', {msg: 'hello wrold'});//触发自定义事件
使用 emit
模拟事件触发。 本例通过模拟click点击事件打开信息窗体
var map = new AMap.Map("container", { resizeEnable: true, zoom: 13 }); var clickHandler = function(e) { log.success("您模拟触发了地图click事件!"); new AMap.InfoWindow({ content:'模拟事件触发', }).open(map,e.lnglat) }; // map.on('click', clickHandler); map.on('complete', function() { // 在地图加载完成时模拟了鼠标点击事件 setTimeout(function(){ // 模拟触发地图click事件 map.emit('click',{ lnglat : map.getCenter() }); },2000) })
批量管理图层
// 初始化实时路况图层 var trafficLayer = new AMap.TileLayer.Traffic({ zIndex: 11 }); // 初始化路网图层 var roadNetLayer = new AMap.TileLayer.RoadNet({ zIndex: 10 }); // 注册图层 var layerGroup = new AMap.LayerGroup([trafficLayer, roadNetLayer]); // 设置图层 layerGroup.setMap(map); layerGroup.show(); // 显示图层 layerGroup.hide(); // 隐藏图层 layerGroup.setOptions({ opacity: Math.random() }) // 设置图层属性 透明度 layerGroup.reload() // 重载图层
图层的添加和移除
var map = new AMap.Map('container', { resizeEnable: true, center: [116.40, 39.91], features: ['road', 'bg'], zoom: 13 }); // 初始化卫星图层 var satellite = new AMap.TileLayer.Satellite({ map: map, }); satellite.setMap(map); // 添加图层 satellite.setMap(null); // 移除图层 satellite.show(); // 显示图层 satellite.hide(); // 隐藏图层 // 设置 zIndex 属性 satellite.setzIndex(z); // 接受一个zIndex数值做参数 satellite.setOpacity(val); // 设置图层透明度 参数 0~1 eg:0.6
高德官方图层
new AMap.TileLayer()
:高德默认标准图层,只显示默认图层的时候,layers可以缺省
var map = new AMap.Map('container', { center: [116.397428, 39.90923], layers: [//只显示默认图层的时候,layers可以缺省 new AMap.TileLayer()//高德默认标准图层 ], zoom: 13 });
new AMap.TileLayer.Traffic
:实时路况图层
var trafficLayer = new AMap.TileLayer.Traffic({ zIndex: 10 }); trafficLayer.setMap(map);
new AMap.TileLayer.Satellite()
: 卫星图new AMap.TileLayer.RoadNet()
:路网图
var map = new AMap.Map('container', { center: [116.397428, 39.90923], layers: [ // 卫星 new AMap.TileLayer.Satellite(), // 路网 new AMap.TileLayer.RoadNet() ], zoom: 13 });
- 楼块图层
var map = new AMap.Map('container', { center: [116.397428, 39.90923], viewMode: '3D', pitch: 60, rotation: -35, // 隐藏默认楼块 features: ['bg', 'road', 'point'], mapStyle: 'amap://styles/light', layers: [ // 高德默认标准图层 new AMap.TileLayer.Satellite(), // 楼块图层 new AMap.Buildings({ zooms: [16, 18], zIndex: 10, heightFactor: 2//2倍于默认高度,3D下有效 }) ], zoom: 16 });
自定义数据图层
- 图片图层
new AMap.ImageLayer()
var imageLayer = new AMap.ImageLayer({ url: 'http://amappc.cn-hangzhou.oss-pub.aliyun-inc.com/lbs/static/img/dongwuyuan.jpg', bounds: new AMap.Bounds( [116.327911, 39.939229], [116.342659, 39.946275] ), zooms: [15, 18] }); var map = new AMap.Map('container', { resizeEnable: true, center: [116.33719, 39.942384], zoom: 15, layers: [ new AMap.TileLayer(), imageLayer ] });
- 视频图层
new AMap.VideoLayer()
&VideoLayer.setMap(map);
var map = new AMap.Map('container', { resizeEnable: true, viewMode: "3D", zoom: 3, center: [115.811491, 12.423935] }); var bounds = new AMap.Bounds([93, -9], [147, 32]); var VideoLayer = new AMap.VideoLayer({ autoplay: true, loop: true, zIndex: 130, //可提供不同格式以达到多浏览器兼容 url: [ 'https://a.amap.com/jsapi_demos/static/video/cloud.m4v', 'https://a.amap.com/jsapi_demos/static/video/cloud.mov' ], bounds: bounds, zooms: [3, 18], opacity: 0.7 }); VideoLayer.setMap(map);
- canvas图层
var map = new AMap.Map('container', { resizeEnable: true, zoom: 15, center: [116.335183, 39.941735] }); var canvas = document.createElement('canvas'); canvas.width = canvas.height = 200; var context = canvas.getContext('2d') context.fillStyle = 'rgb(0,100,255)'; context.strokeStyle = 'white'; context.globalAlpha = 1; context.lineWidth = 2; var radious = 0; var draw = function () { context.clearRect(0, 0, 200, 200) context.globalAlpha = (context.globalAlpha - 0.01 + 1) % 1; radious = (radious + 1) % 100; context.beginPath(); context.arc(100, 100, radious, 0, 2 * Math.PI); context.fill(); context.stroke(); //2D视图时可以省略 CanvasLayer.reFresh(); AMap.Util.requestAnimFrame(draw); }; var CanvasLayer = new AMap.CanvasLayer({ canvas: canvas, bounds: new AMap.Bounds( [116.328911, 39.937229], [116.342659, 39.946275] ), zooms: [3, 18], }); CanvasLayer.setMap(map); draw();
- 自定义图层-canvas
var map = new AMap.Map('container', { center: [116.306206, 39.975468], zooms: [3, 10], zoom:3 }); function getData(callback){ AMap.plugin('AMap.DistrictSearch', function() { var search = new AMap.DistrictSearch(); search.search('中国', function(status, data) { if (status === 'complete') { var positions = [] var provinces = data['districtList'][0]['districtList'] for (var i = 0; i < provinces.length; i += 1) { positions.push({ center: provinces[i].center, radius:10 }) } callback(positions) } }); }); } function addLayer(positions){ AMap.plugin('AMap.CustomLayer', function() { var canvas = document.createElement('canvas'); var customLayer = new AMap.CustomLayer(canvas, { zooms: [3, 10], alwaysRender:true,//缩放过程中是否重绘,复杂绘制建议设为false zIndex: 120 }); var onRender = function(){ var retina = AMap.Browser.retina; var size = map.getSize();//resize var width = size.width; var height = size.height; canvas.style.width = width+'px' canvas.style.height = height+'px' if(retina){//高清适配 width*=2; height*=2; } canvas.width = width; canvas.height = height;//清除画布 var ctx = canvas.getContext("2d"); ctx.fillStyle = '#08f'; ctx.strokeStyle = '#fff'; ctx.beginPath(); for (var i = 0; i < positions.length; i += 1) { var center = positions[i].center; var pos = map.lngLatToContainer(center); var r = positions[i].radius; if(retina){ pos = pos.multiplyBy(2); r*=2 } ctx.moveTo(pos.x+r, pos.y) ctx.arc(pos.x, pos.y, r, 0, 2*Math.PI); } ctx.lineWidth = retina?6:3 ctx.closePath(); ctx.stroke(); ctx.fill(); } customLayer.render = onRender; customLayer.setMap(map); }); } getData(addLayer);
Canvas
作为切片new AMap.TileLayer.Flexible()
var map = new AMap.Map('container', { resizeEnable: true, zoom: 14, zooms: [3, 20], expandZoomRange: true }); var layer = new AMap.TileLayer.Flexible({ cacheSize: 30, zIndex: 200, createTile: function (x, y, z, success, fail) { var c = document.createElement('canvas'); c.width = c.height = 256; var cxt = c.getContext("2d"); cxt.font = "15px Verdana"; cxt.fillStyle = "#ff0000"; cxt.strokeStyle = "#FF0000"; cxt.strokeRect(0, 0, 256, 256); cxt.fillText('(' + [x, y, z].join(',') + ')', 10, 30); // 通知API切片创建完成 success(c); } }); layer.setMap(map);
img
作为切片(模拟水印)
var map = new AMap.Map('container', { resizeEnable: true, zoom: 14, zooms: [3, 20], expandZoomRange: true }); //该demo可模拟水印效果 var layer = new AMap.TileLayer.Flexible({ cacheSize: 30, opacity: 0.3, createTile: function (x, y, z, success, fail) { if ((x + y) % 3) { fail(); return; } // 打散分布 var img = document.createElement('img'); img.onload = function () { success(img) }; // img.crossOrigin = "anonymous";//3D 的时候添加,同时图片要有跨域头 img.onerror = function () { fail() }; img.src = 'https://a.amap.com/jsapi_demos/static/images/amap.png'; } }); layer.setMap(map);
CopyRights: The Post by BY-NC-SA For Authorization,Original If Not Noted,Reprint Please Indicate From NewMiniSoft
Post Link: 高德地图 JS API 常用技巧
Post Link: 高德地图 JS API 常用技巧
发表回复