vue2 高德地图选点使用

完整代码:

<template>

    <div class='vessel'>

        <el-button @click="showMap()">dialogVisible</el-button>

        <el-dialog title="请选择地图定位" :visible.sync="dialogVisible" :close-on-click-modal="false" width="70%">

            <div class="mapBox">

                <div class="searchBox">

                    <el-input style="width:250px;" placeholder="请输入关键字" suffix-icon="el-icon-search"

                        @input="searchByKeyword" @focus="searchByKeyword" size="medium" v-model="keyword">

                    </el-input>

                    <div class="search-result" v-if="searchResult.length && isShowResult">

                        <div class="result-item" v-for="item of searchResult" :key="item.id"

                            @click="handleClickResult(item)">

                            <div class="area-name">{{ item.name }}</div>

                            <div class="area-address">{{ item.district + item.address }}</div>

                        </div>

                    </div>

                </div>

                <div id="container" style="width: 100%;height: 400px;">

                </div>

                <div style="margin-top: 30px;">

                    <el-form :inline="true" :model="loc">

                        <el-form-item label="经度">

                            <el-input style="width: 300px;" v-model="loc.longitude" placeholder="经度"></el-input>

                        </el-form-item>

                        <el-form-item label="纬度">

                            <el-input style="width: 300px;" v-model="loc.latitude" placeholder="纬度"></el-input>

                        </el-form-item>

                        <el-form-item label="地址">

                            <el-input style="width: 300px;" v-model="address" placeholder="详细地址"></el-input>

                        </el-form-item>

                    </el-form>

                </div>

            </div>

            <span slot="footer" class="dialog-footer">

                <el-button @click="dialogVisible = false">取 消</el-button>

                <el-button type="primary" @click="sureSelPoint">确 定</el-button>

            </span>

        </el-dialog>

    </div>

</template>

<script>

/**

 * 使用方法

 * 1.引入

 * import mapSel from "@/components/mapSel.vue";

 * 2.注册

 * components:{

 *     mapSel

 *  },

 * 3.使用

 * <mapSel ref="mapSel" @sendLoc="getLoc"></mapSel>

 * getLoc该方法返回经纬度

 * getLoc(e){

 *     this.ruleForm.lng = e.longitude

 *     this.ruleForm.lat = e.latitude

 *   },

 */

import AMapLoader from '@amap/amap-jsapi-loader'

window._AMapSecurityConfig = {

    securityJsCode: '489759907701cd775d83cc19742f9caf'  //填写你的安全密钥

}

export default {

    name: 'mapSel',

    data() {

        return {

            dialogVisible: false,

            map: null,

            loc: {

                longitude: '',

                latitude: ''

            },

            address: "",

            marker: null,

            autocomplete: null,

            placeSearch: null, //搜索框

            keyword: '',

            searchResult: [],

            isShowResult: false

        }

    },

    mounted() {



    },

    methods: {

        showMap() {

            this.dialogVisible = true

            this.initMap()

        },

        // 点击搜索结果

        handleClickResult(e) {

            const { location, district, address } = e

            const { lng, lat } = location || {}

            // 1. 如果当前搜索结果有经纬度, 直接在地图上选中, 并返回当前的值

            if (lng && lat) {

                this.map.clearMap() //先清空点位

                this.changeValue(lng, lat, e.name, district + address)

                // console.log(location);

                this.marker = new AMap.Marker({

                    position: [lng, lat],

                    zIndex: 102,

                })

                let geocoder = new AMap.Geocoder({});

                var lnglat = new AMap.LngLat(lng, lat);

                geocoder.getAddress(lnglat, (status, result) => {

                    console.log(result);

                    if (status === "complete" && result.regeocode) {

                        this.address = result.regeocode.formattedAddress

                    }

                });

            } else {

                this.isShowResult = false

                this.placeSearch.search(district + address);

            }

        },

        // 输入框搜索显示下拉

        searchByKeyword() {

            this.autocomplete.search(this.keyword, (status, result) => {

                if (status === 'complete' && result.info === 'OK') {

                    this.searchResult = result.tips.map((item) => {

                        return {

                            ...item,

                            address: Array.isArray(item.address) ? (item.address[0] || '') : item.address

                        }

                    })

                    this.isShowResult = true

                }

            })

        },

        // 点击地图

        initMarket(name) {

            this.keyword = ""

            if (!(this.loc.longitude && this.loc.latitude)) {

                return

            }

            this.isShowResult = false

            if (this.map.getAllOverlays('marker').length) {

                // 地图已有标注,清除标注

                this.map.clearMap();

            }



            this.marker = new AMap.Marker({

                position: [this.loc.longitude, this.loc.latitude],

                zIndex: 102,

            })

            console.log(name, "是");



            if (name) {

                // let num = name.length * 4

                // marker.value.setLabel({

                //     offset: new AMap.value.Pixel(-num, 35),

                //     // content: name

                // })

            }

            this.map.add(this.marker)

            // 构造成 LngLat 对象后传入

            var lnglat = new AMap.LngLat(this.loc.longitude, this.loc.latitude);

            // var pixel = this.map.lngLatToContainer(lnglat);

            // console.log(pixel);

            let geocoder = new AMap.Geocoder({});

            geocoder.getAddress(lnglat, (status, result) => {

                console.log(result);

                if (status === "complete" && result.regeocode) {

                    this.address = result.regeocode.formattedAddress

                }

            });

            let distance = this.getMapDistance( 23.357418, 110.06644, this.loc.latitude,this.loc.longitude)

            console.log(`Distance: ${distance.toFixed(2)} km`);

        },

        // 地图初始化

        initMap() {

            AMapLoader.reset()

            AMapLoader.load({

                key: "bf6e6919f136ca56d58ab0980ea7bbcb",             // 申请好的Web端开发者Key,首次调用 load 时必填

                version: "2.0",      // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15

                plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.MarkerClusterer', 'AMap.DistrictSearch', 'AMap.ZoomControl', 'AMap.Polygon', "AMap.Geocoder",],       // 需要使用的的插件列表,如比例尺'AMap.Scale'等

            }).then((AMap) => {

                console.log(AMap, "aaaaaaaaaaaaa数据")

                this.map = new AMap.Map("container", {  //设置地图容器id

                    // viewMode: "3D",    //是否为3D地图模式

                    resizeEnable: true,

                    zoom: 12,           //初始化地图级别

                    center: [114.177253, 22.294622], //初始化地图中心点位置

                });



                this.map.on('click', (e) => {

                    this.loc.latitude = e.lnglat.lat

                    this.loc.longitude = e.lnglat.lng

                    this.initMarket(e)

                })

                var autoOptions = {

                    input: "tipinput"

                };

                this.autocomplete = new AMap.AutoComplete(autoOptions);

                this.placeSearch = new AMap.PlaceSearch({

                    map: this.map

                });

            }).catch(e => {

                console.log(e);

            })

        },

        changeValue(longitude, latitude, name, address) {

            this.isShowResult = false

            this.loc.longitude = longitude

            this.loc.latitude = latitude

            const center = new AMap.LngLat(longitude, latitude);

            // 将地图的中心点移动到指定的经纬度

            this.map.setCenter(center);

            this.marker = new AMap.Marker({

                position: [this.loc.longitude, this.loc.latitude],

                zIndex: 103

            })

            this.map.add(this.marker)

        },

        sureSelPoint() {

            if (this.loc.latitude && this.loc.longitude) {

                this.dialogVisible = false

                this.$emit('sendLoc', this.loc)

            } else {

                this.$message.warning('请选择经纬度')

            }

        },

        /*

         计算距离,参数分别为第一点的纬度,经度;第二点的纬度,经度

         默认单位km

        */

        getMapDistance(lat1, lon1, lat2, lon2) {

                const toRad = (value) => (value * Math.PI) / 180;

                const R = 6371; // 地球半径,单位为公里

                const dLat = toRad(lat2 - lat1);

                const dLon = toRad(lon2 - lon1);

                const a =

                    Math.sin(dLat / 2) * Math.sin(dLat / 2) +

                    Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *

                    Math.sin(dLon / 2) * Math.sin(dLon / 2);

                const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

                const distance = R * c;

                return distance;

        },



    }

}

</script>

<style lang='less' scoped>

::v-deep .el-dialog__body {

    padding: 0px 20px !important;

}



.mapBox {

    position: relative;



    .searchBox {

        position: absolute;

        z-index: 111;

        top: 10px;

        left: 10px;

    }

}



.search-result {

    width: 100%;

    max-height: 300px;

    overflow-y: scroll;

    background-color: #fff;

    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.0600);

    box-sizing: border-box;



    .result-item {

        width: 100%;

        cursor: pointer;

        border-bottom: 2px solid #eee;

        padding: 10px 12px;



        .area-name {

            overflow: hidden;

            text-overflow: ellipsis;

            white-space: nowrap;

            height: 20px;

            color: rgba(0, 0, 0, 0.65);

            font-size: 14px;

            line-height: 20px;

        }



        .area-address {

            color: rgba(0, 0, 0, 0.4500);

            font-size: 12px;

            line-height: 18px;

        }

    }

}

</style>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值