vue+ElementUI+高德API地址模糊搜索(自定義UI組件)

開發環境描述:html

Vue.jsvue

ElementUIapp

高德地圖APIdom

 

需求描述:ecmascript

在新增地址信息的時候,咱們須要根據input輸入的關鍵字調用地圖的輸入提示API,獲取到返回的數據,並根據這些數據生成下拉列表,選擇某一個即獲取當前的地址相關信息(包括位置名稱、經緯度、街區、城市、id等信息)。ide

若是不用鼠標選擇,咱們也能夠按鍵盤上的上下方向鍵移動到目標地址,再按回車鍵選中目標地址。函數

 

 

實現方案分析:ui

1.使用Vue.js,爲了複用性,咱們考慮使用子組件來寫。this

2.當在input中輸入關鍵字的時候,觸發調用地圖接口獲取數據,也就是說要監聽@input事件,在監聽事件的回調函數中調用AMap.Autocomplete插件,搜索返回的數據傳給子組件處理。編碼

3.在子組件中要給每一個地址綁定click事件,點擊後把地址數據返回給父組件,還要給document綁定keydown事件(上、下方向鍵和回車鍵),另外,還要考慮地址下拉浮窗的顯示位置(爲了避免受彈窗dialog的影響,將地址下拉浮窗附加到body元素下,並定位到input框的下方),以及當窗口大小變化(window.onresize)時,須要同時改變地址下拉浮窗的顯示位置。

4.在父組件中也須要給document綁定click事件,當點擊document其餘位置時,隱藏子組件。

5.子組件在選擇地址後,父組件把返回的數據進行處理:當經緯度存在時,直接賦值給相應的變量,當經緯度不存在時(當選擇的是範圍較大的地址時),調用地理編碼API,可獲取粗略的經緯度(好比廣州市,調用地理編碼API會返回廣州市政府的經緯度),若是有須要,還能夠顯示地圖,讓用戶可拖拽選址。

6.在組件銷燬前(beforeDestroy),將document和window綁定的監聽事件解綁。

 

具體實現:

以前寫過一篇相似的隨筆,使用的也是AMap.Autocomplete插件,不過使用的是高德地圖定義好的UI和事件回調,頁面中有幾個地址輸入框,就要定義多少個Autocomplete對象。具體請看這裏

此篇我要寫的是自定義的UI和事件回調。此方法複用性更強一點。

 

父組件:

<template>
    <div style="margin: 50px;width: 300px;">
        <el-form ref="addForm" v-model="addForm" :rules="addRules">
            <el-form-item label="上車地點:" prop="sname">
                <el-input id="sname" v-model.trim="addForm.sname" type="text"
                          @input="placeAutoInput('sname')" @keyup.delete.native="deletePlace('sname')"
                          placeholder="請輸入上車地點">
                    <i
                        class="el-icon-location-outline el-input__icon"
                        slot="suffix" title="上車地點">
                    </i>
                </el-input>
                <div v-show="snameMapShow" class="map-wrapper">
                    <div>
                        <el-button type="text" size="mini" @click.stop="snameMapShow = false">收起<i class="el-icon-caret-top"></i></el-button>
                    </div>
                    <div id="sNameMap" class="map-self"></div></div>
            </el-form-item>
        </el-form>
        <!--地址模糊搜索子組件-->
        <place-search class="place-wrap"
              ref="placeSearch"
              v-if="resultVisible"
              :result="result"
              :left="offsetLeft"
              :top="offsetTop"
              :width="inputWidth"
              :height="inputHeight"
              @getLocation="getPlaceLocation"></place-search>
    </div>
</template>
<script>
    import AMap from 'AMap'
    import placeSearch from './child/placeSearch'

    export default {
        data() {
            let validatePlace = (rules, value, callback) => {
                if (rules.field === 'sname') {
                    if (value === '') {
                        callback(new Error('請輸入上車地點'));
                    } else {
                        if (!this.addForm.slat || this.addForm.slat === 0) {
                            callback(new Error('請搜索並選擇有經緯度的地點'));
                        } else {
                            callback();
                        }
                    }
                }
            };
            return {
                addForm: {
                    sname: '', // 上車地點
                    slat: 0, // 上車地點緯度
                    slon: 0 // 上車地點經度
                },
                addRules: {
                    sname: [{required: true, validator: validatePlace, trigger: 'change'}]
                },
                inputId: '', // 地址搜索input對應的id
                result: [], // 地址搜索結果
                resultVisible: false, // 地址搜索結果顯示標識
                inputWidth: 0, // 搜索框寬度
                inputHeight: 0, // 搜索框高度
                offsetLeft: 0, // 搜索框的左偏移值
                offsetTop: 0, // 搜索框的上偏移值
                snameMap: null,  // 上車地點地圖選址
                snameMapShow: false,  // 上車地點地圖選址顯示
            }
        },
        components: {
            'place-search': placeSearch
        },
        mounted() {
            // document添加onclick監聽,點擊時隱藏地址下拉浮窗
            document.addEventListener("click", this.hidePlaces, false);
            // window添加onresize監聽,當改變窗口大小時同時修改地址下拉浮窗的位置
            window.addEventListener("resize", this.changePos, false)
        },
        methods: {
            placeAutoInput(inputId) {
                let currentDom = document.getElementById(inputId);// 獲取input對象
                let keywords = currentDom.value;
                if(keywords.trim().length === 0) {
                    this.resultVisible = false;
                }
                AMap.plugin('AMap.Autocomplete', () => {
                    // 實例化Autocomplete
                    let autoOptions = {
                        city: '全國'
                    };
                    let autoComplete = new AMap.Autocomplete(autoOptions); // 初始化autocomplete
                    // 開始搜索
                    autoComplete.search(keywords, (status, result) => {
                        // 搜索成功時,result便是對應的匹配數據
                        if(result.info === 'OK') {
                            let sizeObj = currentDom.getBoundingClientRect(); // 取得元素距離窗口的絕對位置
                            this.inputWidth = currentDom.clientWidth;// input的寬度
                            this.inputHeight = currentDom.clientHeight + 2;// input的高度,2是上下border的寬
                            // input元素相對於頁面的絕對位置 = 元素相對於窗口的絕對位置
                            this.offsetTop = sizeObj.top + this.inputHeight; // 距頂部
                            this.offsetLeft = sizeObj.left; // 距左側
                            this.result = result.tips;
                            this.inputId = inputId;
                            this.resultVisible = true;
                        }
                    })
                })
            },
            // 隱藏搜索地址下拉框
            hidePlaces(event) {
                let target = event.target;
                // 排除點擊地址搜索下拉框
                if(target.classList.contains("address")) {
                    return;
                }
                this.resultVisible = false;
            },
            // 修改搜索地址下拉框的位置
            changePos() {
                if(this.inputId && this.$refs['placeSearch']) {
                    let currentDom = document.getElementById(this.inputId);
                    let sizeObj = currentDom.getBoundingClientRect(); // 取得元素距離窗口的絕對位置
                    // 元素相對於頁面的絕對位置 = 元素相對於窗口的絕對位置
                    let inputWidth = currentDom.clientWidth;// input的寬度
                    let inputHeight = currentDom.clientHeight + 2;// input的高度,2是上下border的寬
                    let offsetTop = sizeObj.top + inputHeight; // 距頂部
                    let offsetLeft = sizeObj.left; // 距左側
                    this.$refs['placeSearch'].changePost(offsetLeft, offsetTop, inputWidth, inputHeight);
                }
            },
            // 獲取子組件返回的位置信息
            getPlaceLocation(item) {
                if(item) {
                    this.resultVisible = false;
                    if(item.location && item.location.getLat()) {
this.pickAddress(this.inputId, item.location.getLng(), item.location.getLat()); this.$refs.addForm.validateField(this.inputId); } else { this.geocoder(item.name, this.inputId); } } }, // 地圖選址 pickAddress(inputId, lon, lat) { if(inputId === "sname") { this.snameMapShow = true; AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => { this.snameMap = new AMap.Map('sNameMap', { zoom: 16, scrollWheel: false, center: [lon,lat] }); let positionPicker = new PositionPicker({ mode: 'dragMap', map: this.snameMap }); positionPicker.on('success', (positionResult) => { this.addForm.slat = positionResult.position.lat; this.addForm.slon = positionResult.position.lng; this.addForm.sname = positionResult.address; }); positionPicker.on('fail', (positionResult) => { this.$message.error("地址選取失敗"); }); positionPicker.start(); this.snameMap.addControl(new AMap.ToolBar({ liteStyle: true })); }); } }, // 地理編碼 geocoder(keyword, inputValue) { let geocoder = new AMap.Geocoder({ //city: "010", //城市,默認:「全國」 radius: 1000 //範圍,默認:500 }); //地理編碼,返回地理編碼結果 geocoder.getLocation(keyword, (status, result) => { if (status === 'complete' && result.info === 'OK') { let geocode = result.geocodes; if (geocode && geocode.length > 0) { if (inputValue === "sname") { this.addForm.slat = geocode[0].location.getLat(); this.addForm.slon = geocode[0].location.getLng(); this.addForm.sname = keyword; // 若是地理編碼返回的粗略經緯度數據不須要在地圖上顯示,就不須要調用地圖選址,且要隱藏地圖 // this.pickAddress("sname", geocode[0].location.getLng(), geocode[0].location.getLat()); this.snameMapShow = false; this.$refs.addForm.validateField("sname"); } } } }); }, // 作刪除操做時還原經緯度並驗證字段 deletePlace(inputId) { if (inputId === "sname") { this.addForm.slat = 0; this.addForm.slon = 0; this.$refs.addForm.validateField("sname"); } } }, beforeDestroy() { document.removeEventListener("click", this.hidePlaces, false); } } </script> <style> .map-wrapper .map-self{ height: 150px; } </style>

 

備註:在data()中定義的inputId是爲了保存當前操做的輸入框id,在子組件返回選擇的數據時可根據inputId給該input對應的相關變量賦值,另外,全部的if (inputId === "sname")語句都是爲了防止混淆不一樣input對應的變量(字段),如不須要可刪除此語句。

 

子組件:placeSearch.vue

這裏給每一個元素都加上了一個class:「address」,做用是在document的點擊事件中,若是事件對象含有該class,不隱藏地址下拉浮窗。

另外要注意,API返回的數據雖然都有id、address屬性(不爲空時都是字符串格式),但會出現返回的id、address爲空值(空字符串),故給li設置的key儘可能不要用API返回的id(空值時設置給:key會報錯),而是用自定義的索引值index,當address爲空時,類型是Array(且長度爲0),會顯示[],爲了防止這種狀況,咱們顯示district屬性的值就能夠了。

<template>
    <div class="result-list-wrapper" ref="resultWrapper">
        <ul class="result-list address" :data="result">
            <li class="result-item address"
                v-for="(item, index) in result"
                :key="item.index"
                @click="setLocation(item)"
                ref="resultItem">
                <p class="result-name address" :class="{'active': index === activeIndex}">{{item.name}}</p>
                <template v-if="item.address instanceof Array"><p class="result-adress address">{{item.district}}</p></template>
                <template v-else><p class="result-adress address">{{item.address}}</p></template>
            </li>
        </ul>
    </div>
</template>
<script type="text/ecmascript-6">
    export default {
        props: {
            result: {
                type: Array,
                default: null
            },
            left: { // 輸入框的offsetLeft
                type: Number,
                default: 0
            },
            top: { // 輸入框的offsetTop
                type: Number,
                default: 0
            },
            width: { // 輸入框的寬
                type: Number,
                default: 0
            },
            height: { // 輸入框的高
                type: Number,
                default: 0
            }
        },
        data() {
            return {
                activeIndex: 0 // 激活項
            }
        },
        methods: {
            // 選擇下拉的地址
            setLocation(item) {
                this.$emit('getLocation', item)
            },
            // 初始化地址搜索下拉框位置
            initPos() {
                let dom = this.$refs['resultWrapper'];
                let body = document.getElementsByTagName("body");
                if(body) {
                    body[0].appendChild(dom);
                    let clientHeight = document.documentElement.clientHeight;
                    let wrapHeight = 0;
                    if(this.result && this.result.length>5) {
                        wrapHeight = 250;
                    } else if(this.result && this.result.length<=5) {
                        wrapHeight = this.result.length * 50;
                    }
                    if(clientHeight - this.top < wrapHeight) {
                        // 若是div高度超出底部,div往上移(減去div高度+input高度)
                        dom.style.top = this.top - wrapHeight - this.height + 'px';
                    } else {
                        dom.style.top = this.top + 'px';
                    }
                    dom.style.left = this.left + 'px';
                    dom.style.width = this.width + 'px'
                }
            },
            // 窗口resize時改變下拉框的位置
            changePost(left, top, width, height) {
                let dom = this.$refs['resultWrapper'];
                let clientHeight = document.documentElement.clientHeight;
                let wrapHeight = 0;
                if(this.result && this.result.length>5) {
                    wrapHeight = 250;
                } else if(this.result && this.result.length<=5) {
                    wrapHeight = this.result.length * 50;
                }
                if(clientHeight - top < wrapHeight) {
                    // 若是div高度超出底部,div往上移(減去div高度+input高度)
                    dom.style.top = top - wrapHeight - height + 'px';
                } else {
                    dom.style.top = top + 'px';
                }
                dom.style.left = left + 'px';
                dom.style.width = width + 'px'
            },
            // 監聽鍵盤上下方向鍵並激活當前選項
            keydownSelect(event) {
                let e = event || window.event || arguments.callee.caller.arguments[0];
                if(e && e.keyCode === 38){//
                    if(this.$refs['resultWrapper']) {
                        let items = this.$refs['resultWrapper'].querySelectorAll(".result-item");
                        if(items && items.length>0) {
                            this.activeIndex--;
                            // 滾動條往上滾動
                            if(this.activeIndex < 5) {
                                this.$refs['resultWrapper'].scrollTop = 0
                            }
                            if(this.activeIndex === 5) {
                                this.$refs['resultWrapper'].scrollTop = 250
                            }
                            if(this.activeIndex === -1) {
                                this.activeIndex = 0;
                            }
                        }
                    }
                } else if(e && e.keyCode === 40) {//
                    if(this.$refs['resultWrapper']) {
                        let items = this.$refs['resultWrapper'].querySelectorAll(".result-item");
                        if(items && items.length>0) {
                            this.activeIndex++;
                            // 滾動條往下滾動
                            if(this.activeIndex === 5) {
                                this.$refs['resultWrapper'].scrollTop = 250
                            }
                            if(this.activeIndex === 9) { // 防止最後一條數據顯示不全
                                this.$refs['resultWrapper'].scrollTop = 300
                            }
                            if(this.activeIndex === items.length) {
                                this.activeIndex = 0;
                                this.$refs['resultWrapper'].scrollTop = 0
                            }
                        }
                    }
                } else if(e && e.keyCode === 13) { // 監聽回車事件,並獲取當前選中的地址的經緯度等信息
                    if(this.result && this.result.length > this.activeIndex) {
                        this.setLocation(this.result[this.activeIndex]);
                    }
                }
            }
        },
        mounted() {
            this.initPos();
            document.addEventListener("keydown", this.keydownSelect, false);
        },
        beforeDestroy() {
            document.removeEventListener("keydown", this.keydownSelect, false);
        }
    }
</script>
<style lang="stylus" scoped>
    .result-list-wrapper
        position absolute
        max-height 250px
        overflow auto
        z-index: 9999
        border: 1px solid #ccc
        background-color: #fff
        .result-list
            .result-item
                padding 5px
                color #666
                border-bottom 1px solid #ccc
                &:hover
                    background-color: #f5f5f5
                    cursor pointer
                &:last-child
                    border-bottom none
                .result-name
                    font-size 12px
                    margin-bottom 0.5rem
                    &.active
                        color #259bff
                .result-adress
                    font-size 12px
                    color #bbb
</style>

 

效果圖:

相關文章
相關標籤/搜索