1. 写在前面

之前公司是用的百度的 vue-baidu-map 组件写的一个组件。因为移动端ios默认是高德的地图,Android也是使用的高德的地图,后面没办法pc也需要改高德的地图。花了大半天封装了一个组件。主要功能有分为按关键字搜索地理位置按照经纬度查看地理位置。其他按照关键字搜索很简单,主要是按照经纬度查看地理位置要自己写下。网上找了半天都没有找到。本文主要是下面的效果,好了,继续往下看。。。

点击下载组件代码 vue-gaode-map
在这里插入图片描述

2. vue-amap 高德地图组件引用

vue-amap文档 文档链接地址,需要的小伙伴可以看下,里面很多其他骚操作可能你的需求会用到。

2.1 npm安装 vue-amap

npm install vue-amap --save

2.2 main.js 引入

// 高德的map
import VueAMap from 'vue-amap';
Vue.use(VueAMap);

// 初始化vue-amap,高德的key值需要自己去申请
VueAMap.initAMapApiLoader({
    key: 'cfd8da5cf010c5f7441834ff5e764f5b',
    plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PlaceSearch', 'AMap.Geolocation', 'AMap.Geocoder'],
    v: '1.4.4',
    uiVersion: '1.0'
});

3. 使用 GaodeMap 公共组件

3.1 GaodeMap 组件的功能,可以根据搜索框搜索地理位置,也可以根据经纬度坐标搜索地理位置

点击设置经纬度位置,可以根据搜索框搜索地理位置在这里插入图片描述

点击设置经纬度位置,也可以根据经纬度坐标搜索地理位置
在这里插入图片描述

3.1.1 搜索方法的代码

searchByHand() {
	// 根据关键字搜索,调用searchByKeyword方法调用自带的查询组件
    if (this.radioSearch == 0) {
        if (this.searchKey !== "") {
            this.poiPicker.searchByKeyword(this.searchKey);
        }
    // 根据经纬度查询其他就是重新设置下中心点和,markers的位置
    } else {
        this.center = [this.lng, this.lat]; //设置中心点
        this.markers = []; //清空
        this.markers.push([this.lng, this.lat]); //设置点位置
    }
},

3.2 index.vue 页面代码

<template>
    <div id="app">
        <div class="btns">
            <el-button @click="setAddress('set')">设置经纬度位置</el-button>
            <el-button @click="setAddress('get')">查看经纬度位置</el-button>

            <p>经度:{{ this.point.lng }} &nbsp;维度:{{ this.point.lat }}</p>
            <p>详情位置:{{ this.point.address }}</p>
        </div>
        <el-dialog
            v-if="isShowMap"
            :modal="false"
            :title="!see ? '设置位置' : '查看位置'"
            :visible.sync="isShowMap"
            center
            class="location"
            width="60%"
            @close="clickClose()"
        >
            <div :class="[see ? 'height500' : 'height570']">
                <GaodeMap
                    :see="see"
                    v-if="isShowMap"
                    :lnglat="point"
                    @clickClose="clickClose"
                />
            </div>
        </el-dialog>
    </div>
</template>

<script>
import GaodeMap from "./components/GaodeMap";
export default {
    name: "app",
    components: {
        GaodeMap,
    },
    data() {
        return {
            see: false,
            isShowMap: false,
            point: {
                lng: 121.536353,
                lat: 29.875806,
                address: "浙江省宁波市海曙区西门街道中山西路科创大厦(布政巷)",
            },
        };
    },
    methods: {
        //方法
        setAddress(type) {
            this.isShowMap = true;
            type == "get" ? (this.see = true) : (this.see = false);
        },
        clickClose(data) {
            this.isShowMap = false;
            if (data) {
                console.log(data);
                this.point.lng = data.lng;
                this.point.lat = data.lat;
                this.point.address = data.address;
            }
        },
    },
};
</script>

3.3 GaodeMap.vue 封装的组件代码

<template>
    <div class="mapcontainer">
        <div class="flex-row margin-bottom-10">
            <el-radio-group v-model="radioSearch" v-if="!see">
                <el-radio label="0">按关键字搜索</el-radio>
                <el-radio label="1"> 按坐标搜索</el-radio>
            </el-radio-group>
        </div>
        <el-form ref="ruleForm" class="demo-form-inline" :inline="true">
            <el-form-item class="search-box">
                <el-input
                    v-model="searchKey"
                    v-if="!see"
                    type="search"
                    id="search"
                    style="width: 219px"
                    placeholder="请输入关键字进行搜索"
                    :disabled="radioSearch == '1' ? true : false"
                />
            </el-form-item>
            <div class="tip-box" id="searchTip"></div>
            <el-form-item label="经度" prop="lng">
                <el-input
                    maxlength="11"
                    v-model="lng"
                    style="width: 219px"
                    :disabled="radioSearch == '0' ? true : false"
                ></el-input>
            </el-form-item>
            <el-form-item label="维度:" prop="lat">
                <el-input
                    maxlength="10"
                    v-model="lat"
                    style="width: 219px"
                    :disabled="radioSearch == '0' ? true : false"
                ></el-input>
            </el-form-item>
            <el-form-item>
                <el-button
                    v-if="!see"
                    class="btn submit"
                    type="primary"
                    @click="searchByHand"
                    >搜索</el-button
                >
            </el-form-item>
        </el-form>
        <el-amap
            class="amap-box"
            :amap-manager="amapManager"
            :vid="'amap-vue'"
            :zoom="zoom"
            :plugin="plugin"
            :events="events"
            :center="center"
        >
            <!-- 标记 -->
            <el-amap-marker
                v-for="(marker, index) in markers"
                :position="marker"
                :key="index"
            ></el-amap-marker>
        </el-amap>
        <div class="dialog-footer flex-row flex-center" v-if="!see">
            <el-button
                class="btn submit"
                :disabled="lng == '' || lat == '' ? true : false"
                @click="clickSureMap()"
                >确定</el-button
            >
            <el-button class="btn reset" @click="clickCancleMap()"
                >取消</el-button
            >
        </div>
    </div>
</template>

<script>
import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap";
const amapManager = new AMapManager();
export default {
    name: "Map",
    props: {
        lnglat: {
            default: () => {
                return {
                    lng: "",
                    lat: "",
                };
            },
            type: Object,
        },
        see: {
            type: Boolean,
            default: false,
        }, //为true则是查看位置
    },
    data() {
        const self = this;
        return {
            radioSearch: "0",
            address: null,
            searchKey: "",
            amapManager,
            markers: [],
            searchOption: {
                city: "宁波",
                citylimit: true,
            },
            center: [121.329402, 31.228667],
            zoom: 12,
            lng: 0,
            lat: 0,
            loaded: false,
            events: {
                init() {
                    lazyAMapApiLoaderInstance.load().then(() => {
                        self.initSearch();
                    });
                },
                // 点击获取地址的数据
                click(e) {
                    self.markers = [];
                    const { lng, lat } = e.lnglat;
                    self.lng = lng;
                    self.lat = lat;
                    self.center = [lng, lat];
                    self.markers.push([lng, lat]);
                    // 这里通过高德 SDK 完成。
                    const 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) {
                                self.address =
                                    result.regeocode.formattedAddress;
                                self.searchKey =
                                    result.regeocode.formattedAddress;
                                self.$nextTick();
                                const poi = result.regeocode.addressComponent;
                                const d = {
                                    pos: [lng, lat],
                                    adname: poi.district,
                                    // name: poi.name,
                                    address: self.address,
                                };

                                self.$emit("poi", d);
                            }
                        }
                    });
                },
            },
            // 一些工具插件
            plugin: [
                {
                    // 定位
                    pName: "Geolocation",
                    events: {
                        init(o) {
                            // o是高德地图定位插件实例
                            o.getCurrentPosition((status, result) => {
                                if (result && result.position) {
                                    // 设置经度
                                    self.lng =
                                        self.lnglat.lng || result.position.lng;
                                    // 设置维度
                                    self.lat =
                                        self.lnglat.lat || result.position.lat;
                                    // 设置坐标
                                    self.center = [self.lng, self.lat];
                                    self.markers.push([self.lng, self.lat]);
                                    // load
                                    self.loaded = true;
                                    // 页面渲染好后
                                    self.$nextTick();
                                }
                            });
                        },
                    },
                },
                {
                    // 搜索
                    pName: "PlaceSearch",
                    events: {
                        init(instance) {
                            console.log(instance);
                        },
                    },
                },
            ],
        };
    },
    mounted() {
        this.$nextTick(() => {
            this.searchKey = this.lnglat.address;
            this.center = [this.lnglat.lng, this.lnglat.lat];
        });
    },
    methods: {
        initSearch() {
            const vm = this;
            const map = this.amapManager.getMap();
            AMapUI.loadUI(["misc/PoiPicker"], function (PoiPicker) {
                var poiPicker = new PoiPicker({
                    input: "search",
                    placeSearchOptions: {
                        map: map,
                        pageSize: 11,
                    },
                    suggestContainer: "searchTip",
                    searchResultsContainer: "searchTip",
                });
                vm.poiPicker = poiPicker;
                // 监听poi选中信息
                poiPicker.on("poiPicked", function (poiResult) {
                    const source = poiResult.source;
                    const poi = poiResult.item;
                    if (source !== "search") {
                        poiPicker.searchByKeyword(poi.name);
                    } else {
                        poiPicker.clearSearchResults();
                        vm.markers = [];
                        const lng = poi.location.lng;
                        const lat = poi.location.lat;
                        const address = poi.cityname + poi.adname + poi.name;
                        vm.center = [lng, lat];
                        vm.markers.push([lng, lat]);
                        vm.lng = lng;
                        vm.lat = lat;
                        vm.address = address;
                        vm.searchKey = address;
                        const d = {
                            pos: [lng, lat],
                            adname: poi.adname,
                            name: poi.name,
                            address:
                                poi.pname +
                                " " +
                                poi.cityname +
                                " " +
                                poi.adname +
                                " " +
                                poi.address +
                                " " +
                                poi.name,
                        };
                        vm.$emit("poi", d);
                    }
                });
            });
        },
        searchByHand() {
            if (this.radioSearch == 0) {
                if (this.searchKey !== "") {
                    this.poiPicker.searchByKeyword(this.searchKey);
                }
            } else {
                this.center = [this.lng, this.lat]; //设置中心点
                this.markers = []; //清空
                this.markers.push([this.lng, this.lat]); //设置点位置
            }
        },
        clickSureMap() {
            this.$emit("clickClose", {
                lng: this.lng,
                lat: this.lat,
                address: this.address,
            });
        },
        clickCancleMap() {
            this.$emit("clickClose");
        },
    },
};
</script>
Logo

前往低代码交流专区

更多推荐