高德地图


参考文档:https://lbs.amap.com/demo/amap-ui/demos/amap-ui-districtexplorer/index

1.高德地图使用示例

    

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script
        src="https://webapi.amap.com/maps?v=1.4.15&key=您自己的key&plugin=AMap.Riding,AMap.MouseTool,AMap.PolyEditor,AMap.CircleEditor,AMap.DistrictSearch">
    script>
    <title>Documenttitle>
head>

<body>
    <div id="app">
        <div id="containermap" style="height:400px;width:400px;">

        div>
    div>

body>
<script>
    var communityMap = [
        {
            "keyID": 1,
            "keyDisplay": "116.453844",
            "value": "39.943812",
            "remark": "新街口住户1"
        },
        {
            "keyID": 2,
            "keyDisplay": "117.453844",
            "value": "39.943812",
            "remark": "月坛住户2"
        }
    ]
    // var firstlnt = 111.22, firstlon = 35.12;
    // var firstlnt1 = 112.7, firstlon1 = 38.38;
    var markers = [], lnglatlist = [];
    var arr = []
    communityMap.forEach(item => {
        debugger
        var marker = new AMap.Marker({
            position: new AMap.LngLat(item.keyDisplay, item.value),   // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
            title: item.remark,
        });
        markers.push(marker)
    })
    map = new AMap.Map('containermap', {
        resizeEnable: true, //是否监控地图容器尺寸变化
        zoom: 7, //初始化地图层级
        center: [communityMap[0].keyDisplay, communityMap[0].value] //初始化地图中心点
    });
    AMap.plugin('AMap.ToolBar', function () {//异步加载插件
        var toolbar = new AMap.ToolBar();
        map.addControl(toolbar);
    });
    map.add(markers);
    mouseTool = new AMap.MouseTool(map);
script>

html>

2.自定义图标

           


doctype html>
<html lang="zh-CN">

<head>
    
    <base href="//webapi.amap.com/ui/1.1/ui/overlay/SimpleMarker/examples/" />
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>自定义图标title>
    <style>
    html,
    body,
    #container {
        width: 100%;
        height: 100%;
        margin: 0px;
    }
    
    #myIcon {
        background: orange;
        width: 20px;
        height: 60px;
        border-radius: 10px;
    }
    style>
head>

<body>
    <div id="container">div>
    <div style="display:none">
        <div id="myIcon">div>
    div>
    <script type="text/javascript" src='//webapi.amap.com/maps?v=2.0&key=您自己的key'>script>
    
    <script src="//webapi.amap.com/ui/1.1/main.js?v=1.1.1">script>
    <script type="text/javascript">
    //创建地图
    var map = new AMap.Map('container', {
        zoom: 4
    });


    AMapUI.loadUI(['overlay/SimpleMarker'], function(SimpleMarker) {

        var lngLats = getGridLngLats(map.getCenter(), 5, 5);

        new SimpleMarker({
            iconLabel: '1',
            //自定义图标地址
            iconStyle: '//webapi.amap.com/theme/v1.3/markers/b/mark_r.png',

            //设置基点偏移
            offset: new AMap.Pixel(-19, -60),

            map: map,

            showPositionPoint: true,
            position: lngLats[0],
            zIndex: 100
        });

        new SimpleMarker({
            iconLabel: '2',
            //自定义图标节点(img)的属性
            iconStyle: {

                src: '//webapi.amap.com/theme/v1.3/markers/b/mark_b.png',
                style: {
                    width: '20px',
                    height: '30px'
                }
            },

            //设置基点偏移
            offset: new AMap.Pixel(-10, -30),

            map: map,
            showPositionPoint: true,
            position: lngLats[1],
            zIndex: 200
        });

        new SimpleMarker({
            iconLabel: '3',
            //自定义图标节点(img)的属性
            iconStyle: {

                src: '//webapi.amap.com/theme/v1.3/markers/b/mark_b.png',
                style: {
                    width: '20px',
                    height: '60px'
                }
            },

            //设置基点偏移
            offset: new AMap.Pixel(-10, -60),

            map: map,
            showPositionPoint: true,
            position: lngLats[2]
        });

        new SimpleMarker({
            iconLabel: '4',
            //直接设置html(需要以"<"开头并且以">"结尾)
            iconStyle: '
', //设置基点偏移 offset: new AMap.Pixel(-10, -60), map: map, showPositionPoint: true, position: lngLats[3] }); new SimpleMarker({ iconLabel: '5', //直接使用dom节点 iconStyle: document.getElementById('myIcon'), //设置基点偏移 offset: new AMap.Pixel(-10, -60), map: map, showPositionPoint: true, position: lngLats[4] }); }); /** * 返回一批网格排列的经纬度 * @param {AMap.LngLat} center 网格中心 * @param {number} colNum 列数 * @param {number} size 总数 * @param {number} cellX 横向间距 * @param {number} cellY 竖向间距 * @return {Array} 返回经纬度数组 */ function getGridLngLats(center, colNum, size, cellX, cellY) { var pxCenter = map.lnglatToPixel(center); var rowNum = Math.ceil(size / colNum); var startX = pxCenter.getX(), startY = pxCenter.getY(); cellX = cellX || 70; cellY = cellY || 70; var lngLats = []; for (var r = 0; r < rowNum; r++) { for (var c = 0; c < colNum; c++) { var x = startX + (c - (colNum - 1) / 2) * (cellX); var y = startY + (r - (rowNum - 1) / 2) * (cellY); lngLats.push(map.pixelToLngLat(new AMap.Pixel(x, y))); if (lngLats.length >= size) { break; } } } return lngLats; } script> body> html>

3.西城区域-反向镂空-自定义图标

doctype html>
<html lang="zh-CN">

<head>
    
    <base href="//webapi.amap.com/ui/1.0/ui/geo/DistrictExplorer/examples/" />
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>行政区浏览title>
    <link rel="stylesheet" type="text/css" href="./area.css">
head>

<body>
    <div id="outer-box" style="width: 500px;height: 500px;">
        <div id="container" tabindex="0">div>
        
    div>
    <script type="text/javascript" src='//webapi.amap.com/maps?v=1.4.15&key=您自己的key'>script>
    
    <script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11">script>
    <script type="text/javascript">
        //创建地图

        var map = new AMap.Map('container', {
            resizeEnable: true,
            rotateEnable: true,
            pitchEnable: true,
            zoom: 11.8,
            pitch: 75,
            rotation: -15,
            viewMode: '3D',//开启3D视图,默认为关闭
            buildingAnimation: true,//楼块出现是否带动画
            expandZoomRange: true,
            zooms: [3, 18],
            center: [116.453844, 39.943812]  // 108.907941,34.2463
        });
    
        //just some colors
        var colors = [
            "#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00",
            "#b82e2e", "#316395", "#994499", "#22aa99", "#aaaa11", "#6633cc", "#e67300", "#8b0707",
            "#651067", "#329262", "#5574a6", "#3b3eac"
        ];

        AMapUI.load(['ui/geo/DistrictExplorer', 'lib/$'], function (DistrictExplorer, $) {
            initPage(DistrictExplorer);
            //创建一个实例
            var districtExplorer = window.districtExplorer = new DistrictExplorer({
                eventSupport: true, //打开事件支持
                map: map
            });

            //当前聚焦的区域
            var currentAreaNode = null;

            //鼠标hover提示内容
            var $tipMarkerContent = $('
'); var tipMarker = new AMap.Marker({ content: $tipMarkerContent.get(0), offset: new AMap.Pixel(0, 0), bubble: true }); //根据Hover状态设置相关样式 function toggleHoverFeature(feature, isHover, position) { tipMarker.setMap(isHover ? map : null); if (!feature) { return; } var props = feature.properties; if (isHover) { //更新提示内容 $tipMarkerContent.html(props.adcode + ': ' + props.name); //更新位置 tipMarker.setPosition(position || props.center); } $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').toggleClass('hover', isHover); //更新相关多边形的样式 var polys = districtExplorer.findFeaturePolygonsByAdcode(props.adcode); for (var i = 0, len = polys.length; i < len; i++) { polys[i].setOptions({ fillOpacity: isHover ? 0.5 : 0.2 }); } } //监听feature的hover事件 districtExplorer.on('featureMouseout featureMouseover', function (e, feature) { toggleHoverFeature(feature, e.type === 'featureMouseover', e.originalEvent ? e.originalEvent.lnglat : null); }); //监听鼠标在feature上滑动 districtExplorer.on('featureMousemove', function (e, feature) { //更新提示位置 tipMarker.setPosition(e.originalEvent.lnglat); }); //feature被点击 districtExplorer.on('featureClick', function (e, feature) { debugger var props = feature.properties; //如果存在子节点 if (props.childrenNum > 0) { //切换聚焦区域 switch2AreaNode(props.adcode); } }); //外部区域被点击 // districtExplorer.on('outsideClick', function(e) { // // districtExplorer.locatePosition(e.originalEvent.lnglat, function(error, routeFeatures) { // // if (routeFeatures && routeFeatures.length > 1) { // //切换到省级区域 // switch2AreaNode(routeFeatures[1].properties.adcode); // } else { // //切换到全国 // switch2AreaNode(100000); // } // // }, { // levelLimit: 2 // }); // }); //绘制区域面板的节点 function renderAreaPanelNode(ele, props, color) { var $box = $('
  • ').addClass('lv_' + props.level); var $h2 = $('

    ').addClass('lv_' + props.level).attr({ 'data-adcode': props.adcode, 'data-level': props.level, 'data-children-num': props.childrenNum || void (0), 'data-center': props.center.join(',') }).html(props.name).appendTo($box); if (color) { $h2.css('borderColor', color); } //如果存在子节点 if (props.childrenNum > 0) { //显示隐藏 $('
    ').appendTo($box); //子区域列表 $('
      ').addClass('sublist lv_' + props.level).appendTo($box); $('
      ').appendTo($box); if (props.level !== 'country') { $box.addClass('hide-sub'); } } $box.appendTo(ele); } //填充某个节点的子区域列表 function renderAreaPanel(areaNode) { var props = areaNode.getProps(); var $subBox = $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').siblings('ul.sublist'); if (!$subBox.length) { //父节点不存在,先创建 renderAreaPanelNode($('#area-tree'), props); $subBox = $('#area-tree').find('ul.sublist'); } if ($subBox.attr('data-loaded') === 'rendered') { return; } $subBox.attr('data-loaded', 'rendered'); var subFeatures = areaNode.getSubFeatures(); //填充子区域 for (var i = 0, len = subFeatures.length; i < len; i++) { renderAreaPanelNode($subBox, areaNode.getPropsOfFeature(subFeatures[i]), colors[i % colors.length]); } } //绘制某个区域的边界 function renderAreaPolygons(areaNode) { //更新地图视野 map.setBounds(areaNode.getBounds(), null, null, true); //清除已有的绘制内容 districtExplorer.clearFeaturePolygons(); //绘制子区域 districtExplorer.renderSubFeatures(areaNode, function (feature, i) { var fillColor = colors[i % colors.length]; var strokeColor = colors[colors.length - 1 - i % colors.length]; debugger return { cursor: 'default', bubble: true, strokeColor: strokeColor, //线颜色 strokeOpacity: 1, //线透明度 strokeWeight: 3, //线宽 fillColor: fillColor, //填充色 fillOpacity: 0.2, //填充透明度 }; }); //绘制父区域 districtExplorer.renderParentFeature(areaNode, { cursor: 'default', bubble: true, strokeColor: 'black', //线颜色 strokeOpacity: 1, //线透明度 strokeWeight: 1, //线宽 fillColor: null, //填充色 fillOpacity: 0.2, //填充透明度 }); } //切换区域后刷新显示内容 function refreshAreaNode(areaNode) { districtExplorer.setHoverFeature(null); renderAreaPolygons(areaNode); //更新选中节点的class var $nodeEles = $('#area-tree').find('h2'); $nodeEles.removeClass('selected'); var $selectedNode = $nodeEles.filter('h2[data-adcode=' + areaNode.getAdcode() + ']').addClass('selected'); //展开下层节点 $selectedNode.closest('li').removeClass('hide-sub'); //折叠下层的子节点 $selectedNode.siblings('ul.sublist').children().addClass('hide-sub'); } //切换区域 function switch2AreaNode(adcode, callback) { if (currentAreaNode && ('' + currentAreaNode.getAdcode() === '' + adcode)) { return; } loadAreaNode(adcode, function (error, areaNode) { if (error) { if (callback) { callback(error); } return; } currentAreaNode = window.currentAreaNode = areaNode; //设置当前使用的定位用节点 districtExplorer.setAreaNodesForLocating([currentAreaNode]); refreshAreaNode(areaNode); if (callback) { callback(null, areaNode); } }); } //加载区域 function loadAreaNode(adcode, callback) { districtExplorer.loadAreaNode(adcode, function (error, areaNode) { if (error) { if (callback) { callback(error); } console.error(error); return; } renderAreaPanel(areaNode); if (callback) { callback(null, areaNode); } }); } // $('#area-tree').on('mouseenter mouseleave', 'h2[data-adcode]', function(e) { // // if (e.type === 'mouseleave') { // districtExplorer.setHoverFeature(null); // return; // } // // var adcode = $(this).attr('data-adcode'); // // districtExplorer.setHoverFeature(currentAreaNode.getSubFeatureByAdcode(adcode)); // }); // $('#area-tree').on('click', 'h2[data-children-num]', function() { // // var adcode = $(this).attr('data-adcode'); // // switch2AreaNode(adcode); // }); // $('#area-tree').on('click', '.showHideBtn', function() { // // var $li = $(this).closest('li'); // // $li.toggleClass('hide-sub'); // // if (!$li.hasClass('hide-sub')) { // // //子节点列表被展开 // var $subList = $li.children('ul.sublist'); // // //尚未加载 // if (!$subList.attr('data-loaded')) { // // $subList.attr('data-loaded', 'loading'); // // $li.addClass('loading'); // // //加载 // loadAreaNode($li.children('h2').attr('data-adcode'), function() { // // $li.removeClass('loading'); // }); // } // } // }); //北京110000 switch2AreaNode(110102); }); AMapUI.loadUI(['overlay/SimpleMarker'], function (SimpleMarker) { var lngLats = getGridLngLats(map.getCenter(), 5, 5); new SimpleMarker({ iconLabel: '新街口住户1', //自定义图标节点(img)的属性 iconStyle: { src: '//webapi.amap.com/theme/v1.3/markers/b/mark_b.png', style: { width: '70px', height: '30px' } }, //设置基点偏移 offset: new AMap.Pixel(-10, -60), map: map, showPositionPoint: true, position: ['116.37', '39.92']//lngLats[2] }); }); function getGridLngLats(center, colNum, size, cellX, cellY) { var pxCenter = map.lnglatToPixel(center); var rowNum = Math.ceil(size / colNum); var startX = pxCenter.getX(), startY = pxCenter.getY(); cellX = cellX || 70; cellY = cellY || 70; var lngLats = []; for (var r = 0; r < rowNum; r++) { for (var c = 0; c < colNum; c++) { var x = startX + (c - (colNum - 1) / 2) * (cellX); var y = startY + (r - (rowNum - 1) / 2) * (cellY); lngLats.push(map.pixelToLngLat(new AMap.Pixel(x, y))); if (lngLats.length >= size) { break; } } } return lngLats; } function getAllRings(feature) { var coords = feature.geometry.coordinates, rings = []; for (var i = 0, len = coords.length; i < len; i++) { rings.push(coords[i][0]); } return rings; } function getLongestRing(feature) { var rings = getAllRings(feature); rings.sort(function(a, b) { return b.length - a.length; }); return rings[0]; } function initPage(DistrictExplorer) { //创建一个实例 var districtExplorer = new DistrictExplorer({ map: map }); var countryCode = 100000, //全国 provCodes = [ // 110000, //北京 // 510000 //四川 ], cityCodes = [ 110102, //哈尔滨 ]; districtExplorer.loadMultiAreaNodes( //只需加载全国和市,全国的节点包含省级 [countryCode].concat(cityCodes), function(error, areaNodes) { var countryNode = areaNodes[0], cityNodes = areaNodes.slice(1); var path = []; //首先放置背景区域,这里是大陆的边界 path.push(getLongestRing(countryNode.getParentFeature())); for (var i = 0, len = provCodes.length; i < len; i++) { //逐个放置需要镂空的省级区域 path.push.apply(path, getAllRings(countryNode.getSubFeatureByAdcode(provCodes[i]))); } for (var i = 0, len = cityNodes.length; i < len; i++) { //逐个放置需要镂空的市级区域 path.push.apply(path, getAllRings(cityNodes[i].getParentFeature())); } //绘制带环多边形 //https://lbs.amap.com/api/javascript-api/reference/overlay#Polygon var polygon = new AMap.Polygon({ bubble: true, lineJoin: 'round', // strokeColor: 'red', //线颜色 strokeOpacity: 0, //线透明度 strokeWeight: 0, //线宽 fillColor: 'rgb(0,54,109)', //填充色 fillOpacity: 0.65, //填充透明度 map: map, path: path }); }); } script> body> html>

  • 4.反向镂空

    
    doctype html>
    <html lang="zh-CN">
    
    <head>
        
        <base href="//webapi.amap.com/ui/1.1/ui/geo/DistrictExplorer/examples/" />
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
        <title>反向镂空区域title>
        <style>
        html,
        body,
        #container {
            width: 100%;
            height: 100%;
            margin: 0px;
        }
        style>
    head>
    
    <body>
        <div id="container">div>
        <script type="text/javascript" src='//webapi.amap.com/maps?v=2.0&key=您自己的key'>script>
        
        <script src="//webapi.amap.com/ui/1.1/main.js?v=1.1.1">script>
        <script type="text/javascript">
        //创建地图
        var map = new AMap.Map('container', {
            cursor: 'default',
            zoom: 4
        });
    
        AMapUI.loadUI(['geo/DistrictExplorer'], function(DistrictExplorer) {
            initPage(DistrictExplorer);
        });
    
        function getAllRings(feature) {
    
            var coords = feature.geometry.coordinates,
                rings = [];
    
            for (var i = 0, len = coords.length; i < len; i++) {
                rings.push(coords[i][0]);
            }
    
            return rings;
        }
    
        function getLongestRing(feature) {
            var rings = getAllRings(feature);
    
            rings.sort(function(a, b) {
                return b.length - a.length;
            });
    
            return rings[0];
        }
    
        function initPage(DistrictExplorer) {
            //创建一个实例
            var districtExplorer = new DistrictExplorer({
                map: map
            });
    
            var countryCode = 100000, //全国
                provCodes = [
                    110000, //北京
                    510000 //四川
                ],
                cityCodes = [
                    230100, //哈尔滨
                    331100 //丽水
                ];
    
            districtExplorer.loadMultiAreaNodes(
                //只需加载全国和市,全国的节点包含省级
                [countryCode].concat(cityCodes),
                function(error, areaNodes) {
    
                    var countryNode = areaNodes[0],
                        cityNodes = areaNodes.slice(1);
    
                    var path = [];
    
                    //首先放置背景区域,这里是大陆的边界
                    path.push(getLongestRing(countryNode.getParentFeature()));
    
    
                    for (var i = 0, len = provCodes.length; i < len; i++) {
                        //逐个放置需要镂空的省级区域
                        path.push.apply(path, getAllRings(countryNode.getSubFeatureByAdcode(provCodes[i])));
                    }
    
                    for (var i = 0, len = cityNodes.length; i < len; i++) {
                        //逐个放置需要镂空的市级区域
                        path.push.apply(path, getAllRings(cityNodes[i].getParentFeature()));
                    }
    
                    //绘制带环多边形
                    //https://lbs.amap.com/api/javascript-api/reference/overlay#Polygon
                    var polygon = new AMap.Polygon({
                        bubble: true,
                        lineJoin: 'round',
                        strokeColor: 'red', //线颜色
                        strokeOpacity: 1, //线透明度
                        strokeWeight: 1, //线宽
                        fillColor: 'black', //填充色
                        fillOpacity: 0.65, //填充透明度
                        map: map,
                        path: path
                    });
                });
        }
        script>
    body>
    
    html>

    5.北京区域-自定义图标

    doctype html>
    <html lang="zh-CN">
    
    <head>
        
        <base href="//webapi.amap.com/ui/1.0/ui/geo/DistrictExplorer/examples/" />
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
        <title>行政区浏览title>
        <link rel="stylesheet" type="text/css" href="./area.css">
    head>
    
    <body>
        <div id="outer-box" style="width: 500px;height: 500px;">
            <div id="container" tabindex="0">div>
            
        div>
        <script type="text/javascript" src='//webapi.amap.com/maps?v=1.4.15&key=您自己的key'>script>
        
        <script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11">script>
        <script type="text/javascript">
            //创建地图
    
            var map = new AMap.Map('container', {
                resizeEnable: true,
                rotateEnable: true,
                pitchEnable: true,
                zoom: 11.8,
                pitch: 75,
                rotation: -15,
                viewMode: '3D',//开启3D视图,默认为关闭
                buildingAnimation: true,//楼块出现是否带动画
                expandZoomRange: true,
                zooms: [3, 18],
                center: [116.453844, 39.943812]  // 108.907941,34.2463
            });
       
            //just some colors
            var colors = [
                "#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00",
                "#b82e2e", "#316395", "#994499", "#22aa99", "#aaaa11", "#6633cc", "#e67300", "#8b0707",
                "#651067", "#329262", "#5574a6", "#3b3eac"
            ];
    
            AMapUI.load(['ui/geo/DistrictExplorer', 'lib/$'], function (DistrictExplorer, $) {
    
                //创建一个实例
                var districtExplorer = window.districtExplorer = new DistrictExplorer({
                    eventSupport: true, //打开事件支持
                    map: map
                });
    
                //当前聚焦的区域
                var currentAreaNode = null;
    
                //鼠标hover提示内容
                var $tipMarkerContent = $('
    '); var tipMarker = new AMap.Marker({ content: $tipMarkerContent.get(0), offset: new AMap.Pixel(0, 0), bubble: true }); //根据Hover状态设置相关样式 function toggleHoverFeature(feature, isHover, position) { tipMarker.setMap(isHover ? map : null); if (!feature) { return; } var props = feature.properties; if (isHover) { //更新提示内容 $tipMarkerContent.html(props.adcode + ': ' + props.name); //更新位置 tipMarker.setPosition(position || props.center); } $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').toggleClass('hover', isHover); //更新相关多边形的样式 var polys = districtExplorer.findFeaturePolygonsByAdcode(props.adcode); for (var i = 0, len = polys.length; i < len; i++) { polys[i].setOptions({ fillOpacity: isHover ? 0.5 : 0.2 }); } } //监听feature的hover事件 districtExplorer.on('featureMouseout featureMouseover', function (e, feature) { toggleHoverFeature(feature, e.type === 'featureMouseover', e.originalEvent ? e.originalEvent.lnglat : null); }); //监听鼠标在feature上滑动 districtExplorer.on('featureMousemove', function (e, feature) { //更新提示位置 tipMarker.setPosition(e.originalEvent.lnglat); }); //feature被点击 districtExplorer.on('featureClick', function (e, feature) { debugger var props = feature.properties; //如果存在子节点 if (props.childrenNum > 0) { //切换聚焦区域 switch2AreaNode(props.adcode); } }); //外部区域被点击 // districtExplorer.on('outsideClick', function(e) { // // districtExplorer.locatePosition(e.originalEvent.lnglat, function(error, routeFeatures) { // // if (routeFeatures && routeFeatures.length > 1) { // //切换到省级区域 // switch2AreaNode(routeFeatures[1].properties.adcode); // } else { // //切换到全国 // switch2AreaNode(100000); // } // // }, { // levelLimit: 2 // }); // }); //绘制区域面板的节点 function renderAreaPanelNode(ele, props, color) { var $box = $('
  • ').addClass('lv_' + props.level); var $h2 = $('

    ').addClass('lv_' + props.level).attr({ 'data-adcode': props.adcode, 'data-level': props.level, 'data-children-num': props.childrenNum || void (0), 'data-center': props.center.join(',') }).html(props.name).appendTo($box); if (color) { $h2.css('borderColor', color); } //如果存在子节点 if (props.childrenNum > 0) { //显示隐藏 $('
    ').appendTo($box); //子区域列表 $('
      ').addClass('sublist lv_' + props.level).appendTo($box); $('
      ').appendTo($box); if (props.level !== 'country') { $box.addClass('hide-sub'); } } $box.appendTo(ele); } //填充某个节点的子区域列表 function renderAreaPanel(areaNode) { var props = areaNode.getProps(); var $subBox = $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').siblings('ul.sublist'); if (!$subBox.length) { //父节点不存在,先创建 renderAreaPanelNode($('#area-tree'), props); $subBox = $('#area-tree').find('ul.sublist'); } if ($subBox.attr('data-loaded') === 'rendered') { return; } $subBox.attr('data-loaded', 'rendered'); var subFeatures = areaNode.getSubFeatures(); //填充子区域 for (var i = 0, len = subFeatures.length; i < len; i++) { renderAreaPanelNode($subBox, areaNode.getPropsOfFeature(subFeatures[i]), colors[i % colors.length]); } } //绘制某个区域的边界 function renderAreaPolygons(areaNode) { //更新地图视野 map.setBounds(areaNode.getBounds(), null, null, true); //清除已有的绘制内容 districtExplorer.clearFeaturePolygons(); //绘制子区域 districtExplorer.renderSubFeatures(areaNode, function (feature, i) { var fillColor = colors[i % colors.length]; var strokeColor = colors[colors.length - 1 - i % colors.length]; debugger return { cursor: 'default', bubble: true, strokeColor: strokeColor, //线颜色 strokeOpacity: 1, //线透明度 strokeWeight: 3, //线宽 fillColor: fillColor, //填充色 fillOpacity: 0.2, //填充透明度 }; }); //绘制父区域 districtExplorer.renderParentFeature(areaNode, { cursor: 'default', bubble: true, strokeColor: 'black', //线颜色 strokeOpacity: 1, //线透明度 strokeWeight: 1, //线宽 fillColor: null, //填充色 fillOpacity: 0.2, //填充透明度 }); } //切换区域后刷新显示内容 function refreshAreaNode(areaNode) { districtExplorer.setHoverFeature(null); renderAreaPolygons(areaNode); //更新选中节点的class var $nodeEles = $('#area-tree').find('h2'); $nodeEles.removeClass('selected'); var $selectedNode = $nodeEles.filter('h2[data-adcode=' + areaNode.getAdcode() + ']').addClass('selected'); //展开下层节点 $selectedNode.closest('li').removeClass('hide-sub'); //折叠下层的子节点 $selectedNode.siblings('ul.sublist').children().addClass('hide-sub'); } //切换区域 function switch2AreaNode(adcode, callback) { if (currentAreaNode && ('' + currentAreaNode.getAdcode() === '' + adcode)) { return; } loadAreaNode(adcode, function (error, areaNode) { if (error) { if (callback) { callback(error); } return; } currentAreaNode = window.currentAreaNode = areaNode; //设置当前使用的定位用节点 districtExplorer.setAreaNodesForLocating([currentAreaNode]); refreshAreaNode(areaNode); if (callback) { callback(null, areaNode); } }); } //加载区域 function loadAreaNode(adcode, callback) { districtExplorer.loadAreaNode(adcode, function (error, areaNode) { if (error) { if (callback) { callback(error); } console.error(error); return; } renderAreaPanel(areaNode); if (callback) { callback(null, areaNode); } }); } // $('#area-tree').on('mouseenter mouseleave', 'h2[data-adcode]', function(e) { // // if (e.type === 'mouseleave') { // districtExplorer.setHoverFeature(null); // return; // } // // var adcode = $(this).attr('data-adcode'); // // districtExplorer.setHoverFeature(currentAreaNode.getSubFeatureByAdcode(adcode)); // }); // $('#area-tree').on('click', 'h2[data-children-num]', function() { // // var adcode = $(this).attr('data-adcode'); // // switch2AreaNode(adcode); // }); // $('#area-tree').on('click', '.showHideBtn', function() { // // var $li = $(this).closest('li'); // // $li.toggleClass('hide-sub'); // // if (!$li.hasClass('hide-sub')) { // // //子节点列表被展开 // var $subList = $li.children('ul.sublist'); // // //尚未加载 // if (!$subList.attr('data-loaded')) { // // $subList.attr('data-loaded', 'loading'); // // $li.addClass('loading'); // // //加载 // loadAreaNode($li.children('h2').attr('data-adcode'), function() { // // $li.removeClass('loading'); // }); // } // } // }); //北京110000 switch2AreaNode(110000); }); AMapUI.loadUI(['overlay/SimpleMarker'], function (SimpleMarker) { var lngLats = getGridLngLats(map.getCenter(), 5, 5); new SimpleMarker({ iconLabel: '新街口住户1', //自定义图标节点(img)的属性 iconStyle: { src: '//webapi.amap.com/theme/v1.3/markers/b/mark_b.png', style: { width: '70px', height: '30px' } }, //设置基点偏移 offset: new AMap.Pixel(-10, -60), map: map, showPositionPoint: true, position: ['116.453844', '39.943812']//lngLats[2] }); }); function getGridLngLats(center, colNum, size, cellX, cellY) { var pxCenter = map.lnglatToPixel(center); var rowNum = Math.ceil(size / colNum); var startX = pxCenter.getX(), startY = pxCenter.getY(); cellX = cellX || 70; cellY = cellY || 70; var lngLats = []; for (var r = 0; r < rowNum; r++) { for (var c = 0; c < colNum; c++) { var x = startX + (c - (colNum - 1) / 2) * (cellX); var y = startY + (r - (rowNum - 1) / 2) * (cellY); lngLats.push(map.pixelToLngLat(new AMap.Pixel(x, y))); if (lngLats.length >= size) { break; } } } return lngLats; } script> body> html>

  • 6.北京区域-反向镂空

    doctype html>
    <html lang="zh-CN">
    
    <head>
        
        <base href="//webapi.amap.com/ui/1.0/ui/geo/DistrictExplorer/examples/" />
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
        <title>行政区浏览title>
        <link rel="stylesheet" type="text/css" href="./area.css">
    head>
    
    <body>
        <div id="outer-box" style="width: 500px;height: 500px;">
            <div id="container" tabindex="0">div>
            
        div>
        <script type="text/javascript" src='//webapi.amap.com/maps?v=1.4.15&key=您自己的key'>script>
        
        <script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11">script>
        <script type="text/javascript">
            //创建地图
    
            var map = new AMap.Map('container', {
                resizeEnable: true,
                rotateEnable: true,
                pitchEnable: true,
                zoom: 11.8,
                pitch: 75,
                rotation: -15,
                viewMode: '3D',//开启3D视图,默认为关闭
                buildingAnimation: true,//楼块出现是否带动画
                expandZoomRange: true,
                zooms: [3, 18],
                center: [116.453844, 39.943812]  // 108.907941,34.2463
            });
    
            //just some colors
            var colors = [
                "#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00",
                "#b82e2e", "#316395", "#994499", "#22aa99", "#aaaa11", "#6633cc", "#e67300", "#8b0707",
                "#651067", "#329262", "#5574a6", "#3b3eac"
            ];
    
            AMapUI.load(['ui/geo/DistrictExplorer', 'lib/$'], function (DistrictExplorer, $) {
                initPage(DistrictExplorer);
                //创建一个实例
                var districtExplorer = window.districtExplorer = new DistrictExplorer({
                    eventSupport: true, //打开事件支持
                    map: map
                });
    
                //当前聚焦的区域
                var currentAreaNode = null;
    
                //鼠标hover提示内容
                var $tipMarkerContent = $('
    '); var tipMarker = new AMap.Marker({ content: $tipMarkerContent.get(0), offset: new AMap.Pixel(0, 0), bubble: true }); //根据Hover状态设置相关样式 function toggleHoverFeature(feature, isHover, position) { tipMarker.setMap(isHover ? map : null); if (!feature) { return; } var props = feature.properties; if (isHover) { //更新提示内容 $tipMarkerContent.html(props.adcode + ': ' + props.name); //更新位置 tipMarker.setPosition(position || props.center); } $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').toggleClass('hover', isHover); //更新相关多边形的样式 var polys = districtExplorer.findFeaturePolygonsByAdcode(props.adcode); for (var i = 0, len = polys.length; i < len; i++) { polys[i].setOptions({ fillOpacity: isHover ? 0.5 : 0.2 }); } } //监听feature的hover事件 districtExplorer.on('featureMouseout featureMouseover', function (e, feature) { toggleHoverFeature(feature, e.type === 'featureMouseover', e.originalEvent ? e.originalEvent.lnglat : null); }); //监听鼠标在feature上滑动 districtExplorer.on('featureMousemove', function (e, feature) { //更新提示位置 tipMarker.setPosition(e.originalEvent.lnglat); }); //feature被点击 districtExplorer.on('featureClick', function (e, feature) { debugger var props = feature.properties; //如果存在子节点 if (props.childrenNum > 0) { //切换聚焦区域 switch2AreaNode(props.adcode); } }); //外部区域被点击 // districtExplorer.on('outsideClick', function(e) { // // districtExplorer.locatePosition(e.originalEvent.lnglat, function(error, routeFeatures) { // // if (routeFeatures && routeFeatures.length > 1) { // //切换到省级区域 // switch2AreaNode(routeFeatures[1].properties.adcode); // } else { // //切换到全国 // switch2AreaNode(100000); // } // // }, { // levelLimit: 2 // }); // }); //绘制区域面板的节点 function renderAreaPanelNode(ele, props, color) { var $box = $('
  • ').addClass('lv_' + props.level); var $h2 = $('

    ').addClass('lv_' + props.level).attr({ 'data-adcode': props.adcode, 'data-level': props.level, 'data-children-num': props.childrenNum || void (0), 'data-center': props.center.join(',') }).html(props.name).appendTo($box); if (color) { $h2.css('borderColor', color); } //如果存在子节点 if (props.childrenNum > 0) { //显示隐藏 $('
    ').appendTo($box); //子区域列表 $('
      ').addClass('sublist lv_' + props.level).appendTo($box); $('
      ').appendTo($box); if (props.level !== 'country') { $box.addClass('hide-sub'); } } $box.appendTo(ele); } //填充某个节点的子区域列表 function renderAreaPanel(areaNode) { var props = areaNode.getProps(); var $subBox = $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').siblings('ul.sublist'); if (!$subBox.length) { //父节点不存在,先创建 renderAreaPanelNode($('#area-tree'), props); $subBox = $('#area-tree').find('ul.sublist'); } if ($subBox.attr('data-loaded') === 'rendered') { return; } $subBox.attr('data-loaded', 'rendered'); var subFeatures = areaNode.getSubFeatures(); //填充子区域 for (var i = 0, len = subFeatures.length; i < len; i++) { renderAreaPanelNode($subBox, areaNode.getPropsOfFeature(subFeatures[i]), colors[i % colors.length]); } } //绘制某个区域的边界 function renderAreaPolygons(areaNode) { //更新地图视野 map.setBounds(areaNode.getBounds(), null, null, true); //清除已有的绘制内容 districtExplorer.clearFeaturePolygons(); //绘制子区域 districtExplorer.renderSubFeatures(areaNode, function (feature, i) { var fillColor = colors[i % colors.length]; var strokeColor = colors[colors.length - 1 - i % colors.length]; debugger return { cursor: 'default', bubble: true, strokeColor: strokeColor, //线颜色 strokeOpacity: 1, //线透明度 strokeWeight: 3, //线宽 fillColor: fillColor, //填充色 fillOpacity: 0.2, //填充透明度 }; }); //绘制父区域 districtExplorer.renderParentFeature(areaNode, { cursor: 'default', bubble: true, strokeColor: 'black', //线颜色 strokeOpacity: 1, //线透明度 strokeWeight: 1, //线宽 fillColor: null, //填充色 fillOpacity: 0.2, //填充透明度 }); } //切换区域后刷新显示内容 function refreshAreaNode(areaNode) { districtExplorer.setHoverFeature(null); renderAreaPolygons(areaNode); //更新选中节点的class var $nodeEles = $('#area-tree').find('h2'); $nodeEles.removeClass('selected'); var $selectedNode = $nodeEles.filter('h2[data-adcode=' + areaNode.getAdcode() + ']').addClass('selected'); //展开下层节点 $selectedNode.closest('li').removeClass('hide-sub'); //折叠下层的子节点 $selectedNode.siblings('ul.sublist').children().addClass('hide-sub'); } //切换区域 function switch2AreaNode(adcode, callback) { if (currentAreaNode && ('' + currentAreaNode.getAdcode() === '' + adcode)) { return; } loadAreaNode(adcode, function (error, areaNode) { if (error) { if (callback) { callback(error); } return; } currentAreaNode = window.currentAreaNode = areaNode; //设置当前使用的定位用节点 districtExplorer.setAreaNodesForLocating([currentAreaNode]); refreshAreaNode(areaNode); if (callback) { callback(null, areaNode); } }); } //加载区域 function loadAreaNode(adcode, callback) { districtExplorer.loadAreaNode(adcode, function (error, areaNode) { if (error) { if (callback) { callback(error); } console.error(error); return; } renderAreaPanel(areaNode); if (callback) { callback(null, areaNode); } }); } // $('#area-tree').on('mouseenter mouseleave', 'h2[data-adcode]', function(e) { // // if (e.type === 'mouseleave') { // districtExplorer.setHoverFeature(null); // return; // } // // var adcode = $(this).attr('data-adcode'); // // districtExplorer.setHoverFeature(currentAreaNode.getSubFeatureByAdcode(adcode)); // }); // $('#area-tree').on('click', 'h2[data-children-num]', function() { // // var adcode = $(this).attr('data-adcode'); // // switch2AreaNode(adcode); // }); // $('#area-tree').on('click', '.showHideBtn', function() { // // var $li = $(this).closest('li'); // // $li.toggleClass('hide-sub'); // // if (!$li.hasClass('hide-sub')) { // // //子节点列表被展开 // var $subList = $li.children('ul.sublist'); // // //尚未加载 // if (!$subList.attr('data-loaded')) { // // $subList.attr('data-loaded', 'loading'); // // $li.addClass('loading'); // // //加载 // loadAreaNode($li.children('h2').attr('data-adcode'), function() { // // $li.removeClass('loading'); // }); // } // } // }); //北京110000 switch2AreaNode(110000); }); AMapUI.loadUI(['overlay/SimpleMarker'], function (SimpleMarker) { var lngLats = getGridLngLats(map.getCenter(), 5, 5); new SimpleMarker({ iconLabel: '新街口住户1', //自定义图标节点(img)的属性 iconStyle: { src: '//webapi.amap.com/theme/v1.3/markers/b/mark_b.png', style: { width: '70px', height: '30px' } }, //设置基点偏移 offset: new AMap.Pixel(-10, -60), map: map, showPositionPoint: true, position: ['116.453844', '39.943812']//lngLats[2] }); }); function getGridLngLats(center, colNum, size, cellX, cellY) { var pxCenter = map.lnglatToPixel(center); var rowNum = Math.ceil(size / colNum); var startX = pxCenter.getX(), startY = pxCenter.getY(); cellX = cellX || 70; cellY = cellY || 70; var lngLats = []; for (var r = 0; r < rowNum; r++) { for (var c = 0; c < colNum; c++) { var x = startX + (c - (colNum - 1) / 2) * (cellX); var y = startY + (r - (rowNum - 1) / 2) * (cellY); lngLats.push(map.pixelToLngLat(new AMap.Pixel(x, y))); if (lngLats.length >= size) { break; } } } return lngLats; } function getAllRings(feature) { var coords = feature.geometry.coordinates, rings = []; for (var i = 0, len = coords.length; i < len; i++) { rings.push(coords[i][0]); } return rings; } function getLongestRing(feature) { var rings = getAllRings(feature); rings.sort(function(a, b) { return b.length - a.length; }); return rings[0]; } function initPage(DistrictExplorer) { //创建一个实例 var districtExplorer = new DistrictExplorer({ map: map }); var countryCode = 100000, //全国 provCodes = [ 110000, //北京 ], cityCodes = [ 230100, //哈尔滨 331100 //丽水 ]; districtExplorer.loadMultiAreaNodes( //只需加载全国和市,全国的节点包含省级 [countryCode].concat(cityCodes), function (error, areaNodes) { var countryNode = areaNodes[0], cityNodes = areaNodes.slice(1); var path = []; //首先放置背景区域,这里是大陆的边界 path.push(getLongestRing(countryNode.getParentFeature())); for (var i = 0, len = provCodes.length; i < len; i++) { //逐个放置需要镂空的省级区域 path.push.apply(path, getAllRings(countryNode.getSubFeatureByAdcode(provCodes[i]))); } for (var i = 0, len = cityNodes.length; i < len; i++) { //逐个放置需要镂空的市级区域 path.push.apply(path, getAllRings(cityNodes[i].getParentFeature())); } //绘制带环多边形 //https://lbs.amap.com/api/javascript-api/reference/overlay#Polygon var polygon = new AMap.Polygon({ bubble: true, lineJoin: 'round', strokeColor: 'red', //线颜色 strokeOpacity: 1, //线透明度 strokeWeight: 1, //线宽 fillColor: 'black', //填充色 fillOpacity: 0.65, //填充透明度 map: map, path: path }); }); } script> body> html>