vue项目中使用高德地图

最近做的项目中有个地图选择的功能,如下图所示:

所以在此记录下使用方法,望各位大神指导

我的应用 | 高德控制台第一步:去高德官网去创建一个属于自己的地图应用 (得到key和秘钥)我的应用 | 高德控制台

 这是添加的方式:

准备-入门-教程-地图 JS API | 高德地图API

第二步:获取到属于自己的key和秘钥后,下载地图高德:npm install vue-amap --save 

第三步:在main.js中导入 

扫描二维码关注公众号,回复: 15265442 查看本文章

VueAMap.initAMapApiLoader({
    key: '你申请的key',
    plugin: [
        'AMap.Scale',
        'AMap.OverView',
        'AMap.ToolBar',
        'AMap.MapType',
        'AMap.PlaceSearch',
        'AMap.Geolocation',
        'AMap.Geocoder',
        'AMap.DrivingPolicy',
        'AMap.Driving',
        "AMap.Autocomplete",
   "AMap.PolyEditor",
   "AMap.CircleEditor",
    ],
    v: '1.4.4',
    uiVersion: '1.0',
})

这里的key是你申请的

第四步:index.html页面头部 添加秘钥

​​​​​​​​​​​​​​

<script type="text/javascript">
      window._AMapSecurityConfig = {
          securityJsCode: "你申请的秘钥",
      }
  </script>

 以上步骤完成后,就可以去你对应的页面中使用了

因为我是写的一个组件,所以大家根据自己的情况 

我的组件完整代码:

<template>
    <div class="container">
        <div class="search-box">
            <el-row>
                <el-col :span="16">
                    <el-input v-model="searchKey" id="search" placeholder="请输入地址信息"></el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="success" plain @click="searchByHand" style="margin-left:20px">搜索位置</el-button>
                </el-col>
            </el-row>

            <div class="tip-box" id="searchTip"></div>
        </div>
        <el-amap class="amap-box" :amap-manager="amapManager" :vid="'amap-vue'" :zoom="zoom" :plugin="plugin"
            :center="center" :events="events">
            <!-- 标记 -->
            <el-amap-marker v-for="(marker, index) in markers" :position="marker" :key="index"></el-amap-marker>
        </el-amap>
    </div>
</template>

<script>
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap'
let amapManager = new AMapManager()
export default {
    data() {
        let self = this
        return {
            address: null,
            searchKey: '',
            amapManager,
            markers: [],
            searchOption: {
                city: '全国',
                citylimit: true
            },
            center: [108.872249, 34.33328],
            zoom: 10,
            lng: 0,
            lat: 0,
            loaded: false,
            markerEvent: {
                click(e) {
                    // console.log(e);
                }
            },
            mapInfo: {
                lng: '',
                lat: '',
                mapText: ''
            },
            events: {
                init() {
                    lazyAMapApiLoaderInstance.load().then(() => {
                        self.initSearch()
                    })
                },
                // 点击获取地址的数据
                click(e) {
                    self.markers = []
                    let { lng, lat } = e.lnglat
                    self.lng = lng
                    self.lat = lat
                    self.center = [lng, lat]
                    self.markers.push([lng, lat])
                    // 这里通过高德 SDK 完成。
                    let geocoder = new AMap.Geocoder({
                        radius: 1000,
                        extensions: 'all'
                    })
                    geocoder.getAddress([lng, lat], function (status, result) {//点击地图显示位置信息
                        if (status === 'complete' && result.info === 'OK') {
                            if (result && result.regeocode) {
                                if (result.regeocode.crosses.length > 0) {
                                    self.mapInfo.lng = result.regeocode.crosses[0].location.lng
                                    self.mapInfo.lat = result.regeocode.crosses[0].location.lat
                                }
                                if (result.regeocode.crosses.length > 0) {
                                    self.mapInfo.lng = result.regeocode.pois[0].location.lng
                                    self.mapInfo.lat = result.regeocode.pois[0].location.lat
                                }
                                self.mapInfo.mapText = result.regeocode.formattedAddress
                                // console.log('地图组件中点击选中的地址为',self.mapInfo)
                                if (self.mapInfo.lng !== '' && self.mapInfo.lat !== '') {
                                    self.$store.state.addersInfo = JSON.stringify(self.mapInfo)
                                }
                                console.log(self.lng, self.lat, "33333333333333333")
                                self.address = result.regeocode.formattedAddress
                                self.searchKey = result.regeocode.formattedAddress
                                self.$nextTick()
                            }
                        }
                    })
                }
            },
            // 一些工具插件
            plugin: [
                {
                    // 定位
                    pName: 'Geolocation',
                    events: {
                        init(o) {
                            // o是高德地图定位插件实例
                            o.getCurrentPosition((status, result) => {
                                if (result && result.position) {
                                    // 设置经度
                                    self.lng = result.position.lng
                                    // 设置维度
                                    self.lat = result.position.lat
                                    // 设置坐标
                                    self.center = [self.lng, self.lat]
                                    self.markers.push([self.lng, self.lat])
                                    // load
                                    self.loaded = true
                                    // 页面渲染好后
                                    self.$nextTick()
                                }
                            })
                        },
                        click(e) {
                            // console.log(e);
                        }
                    }
                },
                {
                    // 工具栏
                    pName: 'ToolBar',
                    events: {
                        init(instance) {
                            // console.log(instance);
                        }
                    }
                },
                {
                    // 鹰眼
                    pName: 'OverView',
                    events: {
                        init(instance) {
                            // console.log(instance);
                        }
                    }
                },
                {
                    // 地图类型
                    pName: 'MapType',
                    defaultType: 0,
                    events: {
                        init(instance) {
                            // console.log(instance);
                        }
                    }
                },
                {
                    // 搜索
                    pName: 'PlaceSearch',
                    events: {
                        init(instance) {
                            // console.log(instance)
                        }
                    }
                }
            ]
        }
    },
    created() {
        this.searchKey = JSON.parse(this.$store.state.addersInfo).mapText;
    },
    watch: {
        "$store.state.addersInfo": {
            handler: function (newVal, oldVal) {
                this.searchKey = JSON.parse(newVal).mapText;
            },
            deep : true
        },
        searchKey(addersText) {
            if (addersText == '') {
                this.$store.state.addersInfo = ''
            }
        }
    },
    methods: {
        // submitAddress() {//确定事件
        //     console.log('经纬度', this.center)
        //     console.log('地址', this.address)
        //     this.mapInfo.lng = this.center[0]
        //     this.mapInfo.lat = this.center[1]
        //     this.mapInfo.mapText = this.address
        //     // console.log(this.mapInfo)
        //     this.$store.state.address = JSON.stringify(this.mapInfo)
        // },
        initSearch() {
            let vm = this
            let map = this.amapManager.getMap()
            AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
                var poiPicker = new PoiPicker({
                    input: 'search',
                    placeSearchOptions: {
                        map: map,
                        pageSize: 10
                    },
                    suggestContainer: 'searchTip',
                    searchResultsContainer: 'searchTip'
                })
                console.log(poiPicker, "***********")
                vm.poiPicker = poiPicker
                // 监听poi选中信息
                poiPicker.on('poiPicked', function (poiResult) {
                    let source = poiResult.source
                    let poi = poiResult.item
                    if (source !== 'search') {
                        poiPicker.searchByKeyword(poi.name)
                    } else {
                        poiPicker.clearSearchResults()
                        vm.markers = []
                        let lng = poi.location.lng
                        let lat = poi.location.lat
                        let address = poi.cityname + poi.adname + poi.name
                        vm.center = [lng, lat]
                        // console.log(vm.center)
                        vm.markers.push([lng, lat])
                        vm.lng = lng
                        vm.lat = lat
                        vm.address = address
                        vm.searchKey = address
                        // console.log(vm.address)

                        vm.mapInfo.lng = lng
                        vm.mapInfo.lat = lat
                        vm.mapInfo.mapText = vm.address
                        // console.log(vm.mapInfo)
                        vm.$store.state.addersInfo = JSON.stringify(vm.mapInfo)
                    }
                })
            })
        },
        searchByHand() {//点击搜索事件
            if (this.searchKey !== '') {
                this.searchKey = JSON.parse(this.$store.state.addersInfo).mapText;
                this.poiPicker.searchByKeyword(this.searchKey)
            }
        }
    },

}
</script>

<style lang="scss" scoped>
.container {
    width: 100%;
    height: 500px;
}

.search-box {
    position: absolute;
    z-index: 5;
    width: 100%;
    left: 13%;
    top: 10px;
    height: 30px;
    border: none !important;
}

.tip-box {
    width: 73%;
    max-height: 260px;
    position: absolute;
    top: 42px;
    overflow-y: auto;
    background-color: #fff;
}
</style>

里面都有对应的注释

猜你喜欢

转载自blog.csdn.net/qq_17211063/article/details/127754458