全国地图钻取(openlayers6+高德地图api行政区划)

1、用的是两种方式加载行政范围:全国、陕西、西安用的是本地数据,其他各区域用的是高德行政区划数据。
2、用高德的web服务——行政区划,需要先申请key,个人账户每天可调用3000次。
3、效果如下:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

西安市行政区划

4、完整代码。

<!--
 * @Author: yangxiunan
 * @Date: 2020-10-20 17:06:42
 * @LastEditTime: 2020-10-27 10:20:26
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \cesium-city3dd:\myCode\ol6\src\components\loadJson.vue
-->
<template>
<div class="box">
    <div id="map" class="map"></div>
    <div id="bread">
        <span v-for="item of breadData" :key = "item.code" @click="changeCity(item.code,item.level)">{{item.name}}</span>
    </div>
</div>
</template>
<script>
/* eslint-disable */
import $ from '@/assets/js/jquery-3.5.1.min.js';
import chinaData from '@/assets/data/china_outline.json';
import shanxiData from '@/assets/data/shanxi_outline.json';
import xianData from '@/assets/data/xian_outline.json';
import administrationData from "@/assets/data/administration.json"
import "ol/ol.css";
import Point from 'ol/geom/Point';
import Circle from "ol/geom/Circle";
import LineString from 'ol/geom/LineString';
import Polygon from 'ol/geom/Polygon';
import Feature from "ol/Feature";
import GeoJSON from "ol/format/GeoJSON";
import Map from "ol/Map";
import View from "ol/View";
import XYZ from 'ol/source/XYZ';
import { Circle as CircleStyle, Fill, Stroke, Style, Icon, Text} from "ol/style";
import { OSM, Vector as VectorSource } from "ol/source";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
export default {
    data(){
        return {
            breadData:[
                {name:"中国",code:"100000",level:"country"},
            ]
        }
    },
    mounted() {
        this.vectorLayer = new VectorLayer({
            source: new VectorSource(),
        });
        var map = new Map({
            layers: [
                // new TileLayer({
				// 	source:new XYZ({
				// 		url: 'http://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
                //     }),
				// }),
                this.vectorLayer,
            ],
            target: "map",
            view: new View({
                center: [108.946994,34.261361],
                zoom: 10,
                projection: "EPSG:4326"
            }),
        });
        this.map = map;
        // 默认加载中国
        this.loadFeatures(chinaData);

        map.on('click', evt => {
			this.vectorLayer.getFeatures(evt.pixel).then( features => {
                var feature = features.length ? features[0] : undefined;
                console.log(feature);
                if (feature === undefined) return;
                let properties = feature.getProperties();
                let code = properties.code;
                if(code){
                    this.loadFeatureByCode(code, true, properties);
                }
            })
        });
    },
    
    methods:{
        // 用高德获取该区域数据并加载在地图上
        getGaodeData(city){
            $.ajax({
				dataType:'jsonp',
				url:`https://restapi.amap.com/v3/config/district?keywords=${city}&subdistrict=3&extensions=all&key=您的key`,## 标题
				success:res => {
                    console.log("高德",res);
                    let response = res.districts[0];
                    
                    let center = response.center;
                    let code = response.adcode;
                    center = center.split(",");
                    let name = response.name;
                    let level = response.level;
                    let data=response.polyline;
                    data = data.split("|");

                    data.forEach(polyline=>{
                         polyline = polyline.split(";");
                        let polygon =[];
                        polyline.forEach(item => {
                            let point = item.split(",");
                            polygon.push(point);
                        })

                        let feature = new Feature({
                            geometry:new Polygon([polygon]),
                            name: name,
                            code: code,
                            level: level
                        })
                        feature.setStyle(this.polygonStyle());
                        this.vectorLayer.getSource().addFeature(feature);
                    })
                    this.loadPoint(center, name);
                    this.fitLayer(this.vectorLayer);
                }
            })

        },

        loadFeatureByCode(code,flag = false ,properties = {}){
            let obj = null;
            if(code === "100000"){ //中国
                this.loadFeatures(chinaData);
            }else if(code === "610000"){ //陕西
                this.loadFeatures(shanxiData);
                obj = {
                    name:"陕西省",
                    code:"610000",
                    level:"province",
                }
            }else if(code === "610100"){ //西安市
                this.loadFeatures(xianData);
                obj = {
                    name:"西安市",
                    code:"610100",
                    level:"city",
                }
            }else{
                let codes = this.getChildrenCode(code);
                // 县级没有下级节点
                if(codes.length>0){
                    this.clearLayer(this.vectorLayer);
                    let codes = this.getChildrenCode(code);
                    codes.forEach(code => {
                        this.getGaodeData(code);
                    })
                    obj = {
                        name:properties.name,
                        code:properties.code,
                        level:properties.level,
                    }
                }
            }
            if(flag && obj){
                this.breadData.push(obj);
            }
        },
        // 加载features
        loadFeatures(data){
            this.clearLayer(this.vectorLayer);
            let features = [];
            data.forEach(item => {
                let feature = new Feature({
                    geometry: new Polygon(item.coordinates),
                    name: item.name,
                    center: item.center,
                    code: item.code,
                    level: item.level
                });
                feature.setStyle(this.polygonStyle());
                features.push(feature);
                this.loadPoint(item.center, item.name);
            })
            this.vectorLayer.getSource().addFeatures(features);
            this.fitLayer(this.vectorLayer);
        },
        // 加载地名和点
        loadPoint(point,text){
            let feature = new Feature({
                geometry: new Point(point),
            });
            feature.setStyle(new Style({
                text: new Text({
                    text: text,
                    stroke:new Stroke({
                        color: 'rgba(29,233,182,0)',
                    }),
                    fill:new Fill({
                        color: 'rgba(29,233,182,1)'
                    }),
                    textAlign: 'center',
                    textBaseline: 'bottom',
                }),
            }))
            this.vectorLayer.getSource().addFeature(feature);
        },
        // 清除图层
        clearLayer(layer){
            layer.getSource().clear();
        },
        // 地图自适应图层所在元素的范围
        fitLayer(layer){
            let extent = layer.getSource().getExtent();
            this.map.getView().fit(extent);
        },
        // polygon样式
        polygonStyle(){
            return new Style({
                stroke:new Stroke({
                    color:`rgba(3,199,213,1)`,
                    width:1,
                }),
                fill:new Fill({
                    color:`rgba(19,44,71,1)`,
                })
            })
        },
        // 获取该城市下级城市code
        getChildrenCode(code){
            let result = [];
            administrationData.forEach(item => {
                if(item.code === code){
                    if(item.children.length>0){
                        result = item.children;
                    }
                    return;
                }
                item.children.forEach(v => {
                    if(v.code === code){
                        if(v.children.length>0){
                            result = v.children;
                        }
                        return;
                    }
                })
            }) 
            let codes=[];
            result.forEach(value => {
                codes.push(value.code);
            })
            return codes;
        },
        // 根据城市编码,切换地图
        changeCity(code,level){
            if(level === "country"){
                this.breadData = this.breadData.slice(0,1);
            }else if(level === "province"){
                this.breadData = this.breadData.slice(0,2);
            }else if(level === "city"){
                this.breadData = this.breadData.slice(0,3);
            }
            this.loadFeatureByCode(code);
        },
    },
};
</script>
<style lang="less" scoped>
.box{
    width: 100%;
    height: 100%;
    position: relative;
    background: rgba(9,15,39,1);
    #bread{
        color: #fff;
        position: absolute;
        top: 10px;
        left: 50px;
        
        span{
            padding:0 3px;
            cursor: pointer;
            &:after{
                display: inline-block;
                content:"";
                width:8px;
                height: 8px;
                border-top:1px solid #fff;
                border-right:1px solid #fff;
                transform: rotate(45deg);
            }
            &:last-child{
                &:after{
                    display: none;
                    
                }
            }
        }
    }
    #map {
        width: 100%;
        height: 100%;
    }
}

</style>

4、相关文件
@/assets/data/china_outline.json
@/assets/data/shanxi_outline.json
@/assets/data/xian_outline.json
@/assets/data/administration.json

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值