vue2項目中有用到高德地圖,以此記錄:
需求:搜索可定位地點
過程:在vue2項目運行起地圖,在點圖實現點標記(mark),搜索功能,切換標記
vue-amap官方文檔地址: https://github.com/ElemeFE/vue-amap/
安裝 amap:
npm install vue-amap --save
地圖搭建:
main.js
import VueAMap from "vue-amap" Vue.use(VueAMap) VueAMap.initAMapApiLoader({ key: "xxxxxxxxxxxxxxx", plugin: [ "AMap.Autocomplete", //輸入提示插件 "AMap.PlaceSearch", //POI搜索插件 "AMap.Scale", //右下角縮略圖插件 比例尺 "AMap.OverView", //地圖鷹眼插件 "AMap.ToolBar", //地圖工具條 "AMap.Geolocation", //定位控件,用來獲取和展示用戶主機所在的經緯度位置 "AMap.Geocoder"// 逆地理編碼,通過經緯度獲取地址所在位置詳細信息 // 根據需求選用 ], uiVersion: "1.0", // 地圖ui版本 v : '1.4.4' // amap版本 })
vue文件:
<template> <div class="contain"> <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"> </el-amap-search-box> <el-amap ref="map" vid="amapDemo" :center="center" :zoom="zoom" class="amap-demo"> <el-amap-marker :position="center" key="100"></el-amap-marker> </el-amap> <div v-if="searchResult"> 搜索:{{content}},詳細地址為:{{searchResult.locationName}},經度:{{searchResult.longitude}},緯度:{{searchResult.latitude}} </div> </div> </template> <script> export default { name: 'AMapDemo', data() { return { zoom: 12, center: [118.02, 24.48], searchOption: { // 限制搜索城市的范圍 citylimit: false }, content: '', inputValue: '', searchResult: { address: '', latitude: '', longitude: '', name: '', type: '', country: '', province: '', city: '', area: '', township: '', street: '', neighborhood: '', locationName: '' } } }, methods: { onSearchResult(pois) { //搜索 console.log(pois) let latSum = 0 let lngSum = 0 let that = this if (pois && pois.length > 0) { //如果長度為1則無需轉化 let poi = pois[0] let lng = poi["lng"] let lat = poi["lat"] that.center = [lng, lat] that.zoom = 13 that.content = poi.name console.log(poi.name) that.searchResult.address = poi.address that.searchResult.latitude = poi.lat that.searchResult.longitude = poi.lng let geocoder = new AMap.Geocoder({}) geocoder.getAddress(that.center, function(status, result) { console.log(result) if (status === 'complete' && result.info === 'OK') { let obj = result.regeocode.addressComponent that.searchResult.locationName = obj.province + obj.city + obj.district + obj.township + obj.street + poi.address } }); } else { that.searchResult = [] } }, } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style lang="scss" scoped> .amap-demo { width: 100%; height: 600px; position: relative; } .search-box { height: 35px; margin: 10px auto; width: calc(100% - 20px); // border-radius:16px; box-shadow: none; background: #ffff; border: 1px solid #e6e6e6; .search-box-wrapper { input { background: #fff; padding-left: 20px; } .search-btn { color: #2A67FE; width: 90px; height: 20px; box-sizing: border-box; border-left: 1px solid #D7D7D7; } } } </style>
最終效果如下:
自此,高德地圖完成部署,同時可搜索地點進行標記並且獲取搜索點的經緯度.同時產生了新的功能需求:點擊地圖上的點,進行標記(mark)並且獲取經緯度,下篇進行了記錄