Vue學(xué)習(xí)筆記-高德地圖組件

公司之前一直使用的是百度地圖組件晨川,最近運(yùn)營(yíng)人員一直反映一個(gè)問(wèn)題:有一些地區(qū)在百度地圖上搜不到绽族,地址搜索沒有響應(yīng)。我以為是地圖API版本不對(duì)史煎,更新了版本,這個(gè)問(wèn)題還是存在驳糯。于是我就考慮換一個(gè)地圖組件也解決這個(gè)問(wèn)題篇梭,于是高德就成了我的第一選擇。

準(zhǔn)備工作:

高德開放平臺(tái)酝枢,注冊(cè)成為開發(fā)者恬偷。
高德開發(fā)者平臺(tái)-應(yīng)用.png

申請(qǐng)Key,我申請(qǐng)的是Web端(JS API)帘睦,不同的API效果可能不一樣袍患。

實(shí)現(xiàn)方式:

一:引入 高德坦康,web-sdk (兩種方式)

1:在index.html 中引入

<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.6&key=你申請(qǐng)的高德appKey&plugin=AMap.Walking"></script>

2:安裝vue-amap

Vue-amap基于Vue2.0的高德地圖的地圖組件。

 cnpm install vue-amap --save
二.在webpack.base.conf.js加入
externals: {
    'AMap': 'AMap',
}
三.實(shí)例

1.方式一

<template>
    <div class="hello">
    <el-input id="keyword" name="input" placeholder="請(qǐng)輸入您要定位的位置" v-model="input"></el-input>
    <div style="height:500px" id="container" tabindex="0"></div>
    </div>
</template>

<script>
    import AMap from 'AMap'

    export default {
        name: 'HelloWorld',
        data() {
            return {
                msg: 'hello',
                input: '',
            }
        },
        mounted() {
            this.init();
        },
        methods: {
            init: function () {
                let that = this;
                let map = new AMap.Map('container', {
                    center: [116.397428, 39.90923],
                    resizeEnable: true,
                    zoom: 10,
                    lang: 'ch',
                    keyboardEnable: true
                });
                AMap.plugin('AMap.Geolocation', function () {
                    var geolocation = new AMap.Geolocation({
                        // 是否使用高精度定位诡延,默認(rèn):true
                        enableHighAccuracy: true,
                        // 設(shè)置定位超時(shí)時(shí)間滞欠,默認(rèn):無(wú)窮大
                        timeout: 10000,
                        // 定位按鈕的停靠位置的偏移量肆良,默認(rèn):Pixel(10, 20)
                        buttonOffset: new AMap.Pixel(10, 20),
                        // 定位成功后調(diào)整地圖視野范圍使定位位置及精度范圍視野內(nèi)可見筛璧,默認(rèn):false
                        zoomToAccuracy: true,
                        // 定位按鈕的排放位置, RB表示右下
                        buttonPosition: 'RB'
                    })
                    geolocation.getCurrentPosition()

                    AMap.event.addListener(geolocation, 'complete', (e) => {
                        console.log(e) // 定位成功之后做的事
                        // 定位成功之后再定位處添加一個(gè)marker
                        var marker = new AMap.Marker({
                            position: e.position, // (e.position)--->定位點(diǎn)的點(diǎn)坐標(biāo), position ---> marker的定位點(diǎn)坐標(biāo),也就是marker最終顯示在那個(gè)點(diǎn)上惹恃,
                            icon: '', // marker的圖標(biāo)夭谤,可以自定義,不寫默認(rèn)使用高德自帶的
                            map: map,  // map ---> 要顯示該marker的地圖對(duì)象
                        });
                    });
                    AMap.event.addListener(geolocation, 'error', (e) => {
                        console.log(e) // 定位失敗做的事
                    })
                })
                AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
                    var autoOptions = {
                        city: "北京", //城市巫糙,默認(rèn)全國(guó)
                        input: 'keyword',//使用聯(lián)想輸入的input的id
                    };
                    var autocomplete = new AMap.Autocomplete(autoOptions);
                    var placeSearch = new AMap.PlaceSearch({
                        city: '北京',
                        map: map
                    })
                    AMap.event.addListener(autocomplete, "select", function (e) {
                        //TODO 針對(duì)選中的poi實(shí)現(xiàn)自己的功能
                        placeSearch.setCity(e.poi.adcode);
                        placeSearch.search(e.poi.name)
                    });
                });
                AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function () {
                    map.addControl(new AMap.ToolBar())
                    map.addControl(new AMap.Scale())
                })
            },
        }
    }
</script>

效果如圖:

方式一.1.png
方式一.2.png

2.方式二

封裝一個(gè)mapDrag的組件

<template>
    <div class="m-map">
        <div class="search" v-if="placeSearch">
            <div class="el">
                <el-input placeholder="請(qǐng)輸入您要定位的位置" v-model="searchKey">
                    <el-button @click="handleSearch" icon="el-icon-location" slot="append">搜索</el-button>
                </el-input>
            </div>
            <div id="js-result" v-show="searchKey" class="result"></div>
        </div>
        <div id="js-container" class="map">地圖加載中...</div>
    </div>
</template>

<script>
    import remoteLoad from '@/utils/remoteLoad.js'
    import {MapCityName, MapKey} from '@/config/env'

    export default {
        props: ['lat', 'lng'],
        data() {
            return {
                searchKey: '',
                placeSearch: null,
                dragStatus: false,
                AMapUI: null,
                AMap: null
            }
        },
        watch: {
            searchKey() {
                if (this.searchKey === '') {
                    this.placeSearch.clear()
                }
            }
        },
        methods: {
            // 搜索
            handleSearch() {
                if (this.searchKey) {
                    this.placeSearch.search(this.searchKey)
                }
            },
            // 實(shí)例化地圖
            initMap() {
                // 加載PositionPicker朗儒,loadUI的路徑參數(shù)為模塊名中 'ui/' 之后的部分
                let AMapUI = this.AMapUI = window.AMapUI
                let AMap = this.AMap = window.AMap
                AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
                    let mapConfig = {
                        zoom: 16,
                        cityName: MapCityName,
                        mapStyle: 'amap://styles/55fec7fda8c3e5aeb7b79a2398ba494a', //設(shè)置地圖的顯示樣式
                    }
                    if (this.lat && this.lng) {
                        mapConfig.center = [this.lng, this.lat]
                    }
                    let map = new AMap.Map('js-container', mapConfig)
                    // 加載地圖搜索插件
                    AMap.service('AMap.PlaceSearch', () => {
                        this.placeSearch = new AMap.PlaceSearch({
                            pageSize: 5,
                            pageIndex: 1,
                            citylimit: true,
                            city: MapCityName,
                            map: map,
                            panel: 'js-result'
                        })
                    })
                    // 啟用工具條
                    AMap.plugin(['AMap.ToolBar'], function () {
                        map.addControl(new AMap.ToolBar({
                            position: 'RB'
                        }))
                    })
                    // 創(chuàng)建地圖拖拽
                    let positionPicker = new PositionPicker({
                        mode: 'dragMap', // 設(shè)定為拖拽地圖模式,可選'dragMap'参淹、'dragMarker'醉锄,默認(rèn)為'dragMap'
                        map: map // 依賴地圖對(duì)象
                    })
                    // 拖拽完成發(fā)送自定義 drag 事件
                    positionPicker.on('success', positionResult => {
                        // 過(guò)濾掉初始化地圖后的第一次默認(rèn)拖放
                        if (!this.dragStatus) {
                            this.dragStatus = true
                        } else {
                            this.$emit('drag', positionResult)
                        }
                    })
                    // 啟動(dòng)拖放
                    positionPicker.start()
                })
            }
        },
        async created() {
            // 已載入高德地圖API,則直接初始化地圖
            if (window.AMap && window.AMapUI) {
                this.initMap()
                // 未載入高德地圖API承二,則先載入API再初始化
            } else {
                await remoteLoad(`https://webapi.amap.com/maps?v=1.4.7&key=${MapKey}`)
                await remoteLoad('https://webapi.amap.com/ui/1.0/main.js')
                this.initMap()
            }
        }
    }
</script>

<style lang="css">
    .m-map {
        min-width: 800px;
        min-height: 450px;
        position: relative;
        border: 0.5px solid #b2b2b2;
    }

    .m-map .map {
        width: 100%;
        height: 100%;
    }

    .m-map .search {
        position: absolute;
        top: 10px;
        left: 10px;
        width: 800px;
        z-index: 1;
    }

    .m-map .search .el {
        width: 400px;
        border: 1px solid #ccc;
        line-height: 20px;
        padding: 5px;
        outline: none;
    }

    .m-map .result {
        max-height: 300px;
        max-width: 400px;
        overflow: auto;
        margin-top: 10px;
        z-index: 1;
    }
</style>

在需要使用的地方調(diào)用

<template>
    <div id="app">
        <div class="head">
            <el-input placeholder="當(dāng)前定位的位置"  v-model="dragData.address" readonly class="el-input">
                <el-button @click="submit" icon="el-icon-location" slot="append">確認(rèn)位置</el-button>
            </el-input>
        </div>
        <div class="m-part">
            <mapDrag @drag="dragMap" class="mapbox"></mapDrag>
        </div>
    </div>
</template>

<script>
    import mapDrag from "@/components/GaoDeMap/mapDrag"
    import {getStore, removeStore, setStore} from "@/config/mUtils"

    export default {
        name: 'app',
        components: {
            mapDrag
        },
        data() {
            return {
                dragData: {
                    lng: null,
                    lat: null,
                    address: null,
                    nearestJunction: null,
                    nearestRoad: null,
                    nearestPOI: null
                },
                requestData: {
                    lon: null,
                    lat: null,
                    map_search:null,
                    address: null,
                }
            }
        },
        methods: {
            dragMap(data) {
                console.log(data);
                this.dragData = {
                    lng: data.position.lng,
                    lat: data.position.lat,
                    address: data.address,
                    nearestJunction: data.nearestJunction,
                    nearestRoad: data.nearestRoad,
                    nearestPOI: data.nearestPOI
                }
            },
            submit() {
                console.log(this.dragData);
                this.requestData.lat = this.dragData.lat;
                this.requestData.lon = this.dragData.lng;
                this.requestData.address = this.dragData.address;

                if (typeof (this.requestData.lat) == "undefined" && typeof (this.requestData.lon) == "undefined") {
                    this.requestData.lon = 116.500782;
                    this.requestData.lat = 39.940956;
                    this.requestData.map_search = '智驛信息';
                    this.requestData.address = '北京市朝陽(yáng)區(qū)國(guó)興觀湖國(guó)際-1座';
                }
                if (this.requestData.lat == undefined && this.requestData.lon == undefined) {
                    this.requestData.lon = 116.500748;
                    this.requestData.lat = 39.941108;
                    this.requestData.map_search = '智驛信息';
                    this.requestData.address = '北京市朝陽(yáng)區(qū)國(guó)興觀湖國(guó)際-1座';
                }
                if (this.requestData.lat < 1 || this.requestData.lon < 1) {
                    this.requestData.lon = 116.500748;
                    this.requestData.lat = 39.941108;
                    this.requestData.map_search = '智驛信息';
                    this.requestData.address = '北京市朝陽(yáng)區(qū)國(guó)興觀湖國(guó)際-1座';
                }
                setStore('location', this.requestData);
                this.$emit("close", false)
            },
        }
    }
</script>

<style>
    body {
        margin: 0;
        font-family: "微軟雅黑 Light";
    }

    .head .el-input {
        max-width: 800px;
    }


    .m-part {
        margin-bottom: 30px;
        margin-top: 20px;
    }

    .m-part::after {
        content: '';
        display: block;
        clear: both;
    }

    .m-part .title {
        font-size: 30px;
        line-height: 60px;
        margin-bottom: 10px;
        color: #333;
    }

    .m-part .mapbox {
        width: 600px;
        height: 400px;
        margin-bottom: 20px;
        float: left;
    }
</style>

效果如圖:

方式二.2.png
方式二.1.png

相關(guān)資料:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末榆鼠,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子亥鸠,更是在濱河造成了極大的恐慌妆够,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件负蚊,死亡現(xiàn)場(chǎng)離奇詭異神妹,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)家妆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門鸵荠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人伤极,你說(shuō)我怎么就攤上這事蛹找。” “怎么了哨坪?”我有些...
    開封第一講書人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵庸疾,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我当编,道長(zhǎng)届慈,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮金顿,結(jié)果婚禮上臊泌,老公的妹妹穿的比我還像新娘。我一直安慰自己揍拆,他們只是感情好渠概,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著礁凡,像睡著了一般高氮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上顷牌,一...
    開封第一講書人閱讀 51,598評(píng)論 1 305
  • 那天剪芍,我揣著相機(jī)與錄音,去河邊找鬼窟蓝。 笑死罪裹,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的运挫。 我是一名探鬼主播状共,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼谁帕!你這毒婦竟也來(lái)了峡继?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤匈挖,失蹤者是張志新(化名)和其女友劉穎碾牌,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體儡循,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡舶吗,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了择膝。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片誓琼。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖肴捉,靈堂內(nèi)的尸體忽然破棺而出腹侣,到底是詐尸還是另有隱情,我是刑警寧澤齿穗,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布傲隶,位于F島的核電站,受9級(jí)特大地震影響缤灵,放射性物質(zhì)發(fā)生泄漏伦籍。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一腮出、第九天 我趴在偏房一處隱蔽的房頂上張望帖鸦。 院中可真熱鬧,春花似錦胚嘲、人聲如沸作儿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)攻锰。三九已至,卻和暖如春妓雾,著一層夾襖步出監(jiān)牢的瞬間娶吞,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工械姻, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留妒蛇,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓楷拳,卻偏偏與公主長(zhǎng)得像绣夺,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子欢揖,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • UI組件 element- 餓了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的組件庫(kù) m...
    王喂馬_閱讀 6,454評(píng)論 1 77
  • UI組件 element- 餓了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的組件庫(kù) m...
    小姜先森o0O閱讀 9,487評(píng)論 0 72
  • 基于Vue的一些資料 內(nèi)容 UI組件 開發(fā)框架 實(shí)用庫(kù) 服務(wù)端 輔助工具 應(yīng)用實(shí)例 Demo示例 element★...
    嘗了又嘗閱讀 1,154評(píng)論 0 1
  • UI組件 element- 餓了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的組件庫(kù) m...
    35eeabfa0772閱讀 3,270評(píng)論 7 12
  • UI組件 element - 餓了么出品的Vue2的web UI工具套件 Vux - 基于Vue和WeUI的組...
    魯大師666閱讀 43,398評(píng)論 5 97