高德地图可搜索进行地图打点及自定义拖拽打点

478 阅读1分钟

image.png

卫星图层样式

image.png

1.loadMap.js

/**
 * 动态加载高德地图
 *
 * @export
 * @param {*} key 高德地图key
 * @param {*} plugins 高德地图插件
 * @param {string} [v="1.4.14"] 高德地图版本
 * @returns
 */
/* eslint-disable */
 // export default function loadMap(key, plugins, v = "1.4.14") {
 export default function loadMap(key, plugins, v = "2.0") {
    return new Promise(function(resolve, reject) {
        if (typeof AMap !== "undefined") {
            console.log('AMap', AMap)
            // eslint-disable-next-line no-undef
            resolve(AMap)
            return true
        }
        window.onCallback = function() {
            // eslint-disable-next-line no-undef
            resolve(AMap)
        }
        let script = document.createElement("script")
        script.type = "text/javascript"
        script.src = `https://webapi.amap.com/maps?v=${v}&key=${key}&plugin=${plugins}&callback=onCallback`
        script.onerror = reject
        document.head.appendChild(script)
    })
}
/* eslint-enable */

2.map.js

export default {
    data () {
      return {
        inputContent: '',
        GDMap: null,
        plugins: [
        'AMap.Autocomplete',
        'AMap.PlaceSearch',
        'AMap.OverView',
        'AMap.MouseTool',
        'AMap.PolyEditor',
        'AMap.RectangleEditor',
        'AMap.DistrictLayer',
        'AMap.CustomLayer',
        'AMap.MouseTool',
        'AMap.PlaceSearch',
        'AMap.AutoComplete',
        ],
        key: '申请的key',
        v: '2.0',
      }
    },
    methods: {
    },
}

3.使用

<template>
    <el-dialog
        :title="modalTitle"
        :visible.sync="visible" @close="handleCancel" width="40%">
        <el-row>
            <el-form ref="ExamineAreaEdit" :model="req" label-width="110px">

                <el-col :span="24">
                    <el-form-item label="所属区域" prop="deptName" :rules="[rules.required]">
                        <el-select v-model="req.deptName" clearable size="small" @change="onDeptNameChange">
                            <el-option :label="item.name" :value="item.name"
                                       v-for="(item, index) in deptTreeList"
                                       :key="`deptTreeList-${index}`"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="24">

                    <el-form-item label="检验地点" prop="name" :rules="[rules.required]">
                        <el-input id="tipinput" placeholder="请输入关键字" v-model="req.name" class="amap-page-container" @keyup.native.enter="handelSearch"></el-input>
                    </el-form-item>
                    <el-form-item label="简略地点" prop="simpleArea" :rules="[rules.required]">
                        <el-input v-model="req.simpleArea" :readonly="readonly"></el-input>
                    </el-form-item>
                    <div @click="changeWX" class="GDwx" :style="{color:isWx?'#409EFF': '#909399'}">
                        <div v-if="isWx" class="GDwx_active"></div>
                        <div v-else class="GDwx_icon">
                        </div>
                        <div>卫星</div>
                    </div>
                    <div id="GDMap" style="height:400px;margin-top: 20px"></div>
                    <div id="panel"></div>
                </el-col>
            </el-form>
        </el-row>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSure" :loading="isLoading" v-if="status">确定</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import loadMap from '@/util/loadMap'
    import map from '@/mixins/map.js'
    import {validateObj} from '@/util/validate'
    import {
        adminDeptTree,
        examine_placeAdd,
        examine_placePut,
        examine_placeById,
    } from '@/api/fishInspection/examinePlace'


    export default {
        name: 'ExamineAreaEdit',
        mixins: [map],
        props: {
            // 表单id
            id: {
                type: String,
                default: '',
            },
            // 弹窗状态
            status: {
                type: Number,
            },
            // 弹框状态
            value: {
                type: Boolean,
                default: false,
            },
            // 弹框状态
            show: {
                type: Boolean,
                default: false,
            },
        },
        data () {
            return {
                visible: this.show,
                // 参数
                req: {
                    id: this.id,
                    simpleArea: null, // 简略地点
                    name: null, // 检验地点名称
                    lon: '', // 经度
                    lat: '', // 	纬度
                    deptId: null, // 所属区域id
                    deptName: null, // deptName
                    deptPath: null, // 所属区域路径
                    adcode: null,
                },
                // 归属地列表
                deptTreeList: [],
                // 规则
                rules: {
                    required: {
                        required: true,
                        validator: validateObj.default,
                        message: '该项不可为空',
                        trigger: 'change',
                    },
                },
                mapOptions: {
                    searchOption: {
                        city: '全国',
                        citylimit: false,
                    },
                    mapCenter: [121.59996, 31.197646],
                    marker: [121.59996, 31.197646],
                    plugin: [],
                },

                // 是否受理
                isLoading: false,
                marker: null,
                isWx: false, // 高德卫星

            }
        },
        computed: {
            // eslint-disable-next-line vue/return-in-computed-property
            modalTitle () {
                if (this.status === 0) return '查看'
                if (this.status === 1) return '新增'
                if (this.status === 2) return '编辑'
            },
            // 是否只读 (0=>查看,1=>新增,2=>编辑)
            readonly () {
                return !this.status
            },
        },
        watch: {
            show (newVal) {
                this.visible = newVal
                if (newVal) {
                    this.initLoad()
                } else {
                    this.handleReset()
                }
            },
        },
        methods: {
            changeWX () {
                this.isWx = !this.isWx
                if (!this.id) return this.initLoadMap()
                this.initLoadMap([this.req.lon, this.req.lat])
            },
            //清点生成点方法
            getNewMarker (e, _this, type) {
                //区分是打点还是拖拽   1是地图 2 搜索点传参
                if (_this.marker) {
                    _this.GDMap.remove(_this.marker)
                }
                // eslint-disable-next-line
                _this.marker = new AMap.Marker({
                    position: type == 2 ? [e.poi.location.lng, e.poi.location.lat] : [e.lnglat.lng, e.lnglat.lat],
                    map: _this.GDMap,
                    draggable: true,
                })
                if (type == 2) {
                    let location = e.poi.location
                    _this.req.lat = location.lat
                    _this.req.lon = location.lng
                    _this.req.name = e.poi.name
                    _this.req.adcode = e.poi.adcode
                }else{
                    let location=e.lnglat
                    _this.req.lat = location.lat
                    _this.req.lon =  location.lng
                }
                _this.markerMove(_this)
            },

            markerMove (_this) {
                /* eslint-disable */
                //点拖动事件
                _this.marker.on('dragend', function (e) {
                    //拖拽获取地点  根据经纬度获取地点信息
                    let lngLat = [e.lnglat.lng, e.lnglat.lat]
                    AMap.plugin('AMap.Geocoder', function () {

                        var geocoder = new AMap.Geocoder({
                            // city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
                            city: '全国',
                        })
                        geocoder.getAddress(lngLat, function (status, result) {
                            if (status === 'complete' && result.info === 'OK') {
                                // result为对应的地理位置详细信息
                                console.log(result)
                                let location = e.lnglat
                                _this.req.lat = location.lat
                                _this.req.lon = location.lng
                                _this.req.name = result.regeocode.formattedAddress
                                _this.req.adcode = result.regeocode.adcode

                            }
                        })
                    })

                })
            },

            handleReset () {
                this.req = this.$options.data().req
                this.$refs.ExamineAreaEdit.resetFields()
            },
            onDeptNameChange (value) {
                let target = this.deptTreeList.find(item => item.name === value)
                this.req.deptId = target.id
                this.req.deptPath = target.deptPath
            },
            handleCancel () {
                this.visible = false
                this.$emit('input', false)
                this.$emit('update:show', false)
            },
            initLoad () {
                this.loadData()
                this.loadDeptTree()
            },
            onSearchResult (pois) {
                this.mapOptions.mapCenter = [pois[0].lng, pois[0].lat]
                this.mapOptions.marker = [pois[0].lng, pois[0].lat]
            },
            // 加载高德地图
            initLoadMap (val) {
                let _this = this
                var layers = []
                if (this.isWx) {
                    layers = [
                        // 卫星
                        new AMap.TileLayer.Satellite(),
                        // 路网
                        new AMap.TileLayer.RoadNet()
                    ]
                } else {
                    layers = []
                }
                /* eslint-disable */
                loadMap(this.key, this.plugins, this.v)
                    .then(AMap => {
                        console.log("地图加载complete!");
                        this.GDMap = new AMap.Map("GDMap", {
                            zoom: 18,
                            center: val || [122.106691, 30.015136],
                            layers: layers,
                        });
                        if (val) {
                            this.marker = new AMap.Marker({
                                position: val,
                                map: _this.GDMap,
                                draggable: true
                            })
                            this.markerMove(this)
                        }

                        this.GDMap.on("complete", () => {
                            console.log("地图加载complete!");
                            AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], () => {
                                let auto = new AMap.Autocomplete({
                                    input: "tipinput",
                                });
                                let placeSearch = new AMap.PlaceSearch({
                                    map: this.GDMap
                                }); //构造地点查询类
                                // console.log('this.mapAuto', this.mapAuto)
                                console.log('this.placeSearch', placeSearch)
                                auto.on("select", select);//注册监听,当选中某条记录时会触发
                                function select(e) {
                                    placeSearch.setCity(e.poi.adcode);
                                    placeSearch.search(e.poi.name, () => {
                                        _this.GDMap.clearMap()
                                        _this.getNewMarker(e, _this, 2)
                                    });  //关键字查询查询
                                }
                            })

                        });
                        //地图打点
                        this.GDMap.on('click', function (e) {
                            _this.getNewMarker(e, _this, 1)
                        })
                    })
                    .catch(() => {
                        console.log("地图加载失败!");
                    });
            },
            // 加载所属区域
            loadDeptTree() {
                adminDeptTree().then(({data}) => {
                    this.deptTreeList = data.data
                })
            },
            // 加载数据
            loadData() {
                this.isWx = false
                this.initLoadMap([this.req.lon, this.req.lat])
            },
            // 按钮触发检索
            handelSearch(e) {
                this.mapAuto.on("select", select);//注册监听,当选中某条记录时会触发
                function select(e) {
                   console.log('e', e)
                   placeSearch.setCity(e.poi.adcode);
                   placeSearch.search(e.poi.name);  //关键字查询查询
                }
            },
            handleSure() {
                this.$refs.ExamineAreaEdit.validate((valid) => {
                    if (valid) {
                        this.isLoading = true
                        let Api = this.req.id ? examine_placePut : examine_placeAdd
                        let params = JSON.parse(JSON.stringify(this.req))
                    }
                })
            }
        },
        mounted() {
            this.initLoad()
        }
    }
</script>

<style scoped>

</style>
<style>
    .amap-page-container {
        position: relative;
    }

    .amap-logo {
        display: none;
    }

    .amap-sug-result {
        z-index: 9999999999;
    }
    .GDwx{
        width: 100px;
        height: 36px;
        background: #fff;
        border-radius: 5px;
        font-size: 20px;
        position: absolute;
        z-index: 9;
        right: 10px;
        margin-top: 10px;
        line-height: 26px;
        display: flex;
        align-content: center;
        justify-content: space-around;
        padding: 5px 10px;
    }
    .GDwx_active{
        width: 26px;
        height: 26px;
        background-image: url('/img/icons/icon-active.png');
        background-repeat: no-repeat;
        background-size: 100% 100%;
    }
    .GDwx_icon{
        width: 26px;
        height: 26px;
        background-image: url('/img/icons/icon-wx.png');
        background-repeat: no-repeat;
        background-size: 100% 100%;
    }
</style>