Vue2 高德地图选点(带搜索)

1.下载高德地图的插件

npm i @amap/amap-jsapi-loader 

2.去高德地图开放平台注册key,和安全密钥

3.完整代码示例

<template>
  <div class='vessel'> 
    <el-dialog
        title="请选择地图定位"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        width="70%"
        >
        <div class="mapBox">
            <div class="searchBox">
                <el-input
                    style="width:250px;"
                    placeholder="请输入关键字"
                    suffix-icon="el-icon-search"
                    @input="searchByKeyword"
                    @focus="searchByKeyword"
                    size="medium"
                    v-model="keyword">
                </el-input>
                <div class="search-result"  v-if="searchResult.length && isShowResult">
                    <div class="result-item" v-for="item of searchResult" :key="item.id" @click="handleClickResult(item)">
                        <div class="area-name">{{ item.name }}</div>
                        <div class="area-address">{{ item.district + item.address }}</div>
                    </div>
                </div>
            </div>
            <div id="container" style="width: 100%;height: 400px;">
            </div>
            <div style="margin-top: 30px;">
                <el-form :inline="true" :model="loc">
                    <el-form-item label="经度">
                        <el-input style="width: 300px;" v-model="loc.longitude" placeholder="经度"></el-input>
                    </el-form-item>
                    <el-form-item label="纬度">
                        <el-input  style="width: 300px;" v-model="loc.latitude" placeholder="纬度"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="sureSelPoint">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
/**
 * 使用方法 
 * 1.引入
 * import mapSel from "@/components/mapSel.vue";
 * 2.注册
 * components:{
 *     mapSel
 *  },
 * 3.使用
 * <mapSel ref="mapSel" @sendLoc="getLoc"></mapSel>
 * getLoc该方法返回经纬度
 * getLoc(e){
 *     this.ruleForm.lng = e.longitude
 *     this.ruleForm.lat = e.latitude
 *   },
 */
import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
    securityJsCode: '你的安全密钥'  //填写你的安全密钥
}
export default {
   name: '',
   data() {
      return { 
        dialogVisible:false,
        map: null,
        loc:{
            longitude:'',
            latitude:''
        },
        marker:null,
        autocomplete:null,
        placeSearch:null, //搜索框
        keyword:'',
        searchResult:[],
        isShowResult:false
      }
   },
   mounted() {
   },
   methods: {
        showMap(){
            this.dialogVisible = true
            this.initMap()
        },
        // 点击搜索结果
        handleClickResult(e){
            const { location, district, address } = e
            const { lng, lat } = location || {}
            // 1. 如果当前搜索结果有经纬度, 直接在地图上选中, 并返回当前的值
            if(lng && lat) {
                this.map.clearMap() //先清空点位
                this.changeValue(lng, lat, e.name , district+address)
            }else{
                this.isShowResult = false
                this.placeSearch.search(district+address);
            }
        },
        // 输入框搜索显示下拉
        searchByKeyword() {
            this.autocomplete.search(this.keyword, (status, result) => {
                if (status === 'complete' && result.info === 'OK') {
                    this.searchResult = result.tips.map((item) => {
                        return {
                        ...item,
                        address: Array.isArray(item.address) ? (item.address[0] || '') : item.address
                        }
                    })
                    this.isShowResult = true
                } 
            })
        },
        // 点击地图
        initMarket(name){
            if (!(this.loc.longitude && this.loc.latitude)) {
                return
            }
            this.isShowResult = false
            if (this.map.getAllOverlays('marker').length) {
                // 地图已有标注,清除标注
                this.map.clearMap();
            }
            this.marker = new AMap.Marker({
                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
                position: [this.loc.longitude, this.loc.latitude],
                offset: new AMap.Pixel(-10, -26),
                zIndex: 102
            })
            if (name) {
                let num = name.length * 4
                marker.value.setLabel({
                offset: new AMap.value.Pixel(-num, 35),
                content: name
                })
            }
            this.map.add(this.marker)
        },
        // 地图初始化
        initMap() {
            AMapLoader.reset()
            AMapLoader.load({
                key: "申请好的Web端开发者Key",             // 申请好的Web端开发者Key,首次调用 load 时必填
                version: "2.0",      // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
                plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.MarkerClusterer', 'AMap.DistrictSearch', 'AMap.ZoomControl', 'AMap.Polygon'],       // 需要使用的的插件列表,如比例尺'AMap.Scale'等
            }).then((AMap) => {
                this.map = new AMap.Map("container", {  //设置地图容器id
                    // viewMode: "3D",    //是否为3D地图模式
                    resizeEnable: true,
                    zoom: 12,           //初始化地图级别
                    center: [114.304569, 30.593354], //初始化地图中心点位置
                });

                this.map.on('click', (e) => {
                    this.loc.latitude = e.lnglat.lat
                    this.loc.longitude = e.lnglat.lng
                    this.initMarket()
                })
                var autoOptions = {
                    input: "tipinput"
                };
                this.autocomplete = new AMap.AutoComplete(autoOptions);
                this.placeSearch = new AMap.PlaceSearch({
                    map: this.map
                });  
            }).catch(e => {
                console.log(e);
            })
        },
        changeValue (longitude, latitude,name, address) {
            this.isShowResult = false
            this.loc.longitude = longitude
            this.loc.latitude = latitude
            const center = new AMap.LngLat(longitude, latitude);
            // 将地图的中心点移动到指定的经纬度
            this.map.setCenter(center);
            this.marker = new AMap.Marker({
                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
                position: [this.loc.longitude, this.loc.latitude],
                zIndex: 103
            })
            this.map.add(this.marker)
        },
        sureSelPoint(){
            if(this.loc.latitude && this.loc.longitude){
                this.dialogVisible = false
                this.$emit('sendLoc',this.loc)
            }else{
                this.$message.warning('请选择经纬度')
            }
        }
   }
}
</script>
<style lang='less' scoped>
::v-deep .el-dialog__body{
    padding: 0px 20px!important;
}
.mapBox{
    position: relative;
    .searchBox{
        position: absolute;
        z-index: 111;
        top: 10px;
        left: 10px;
    }
}
.search-result {
    width: 100%;
    max-height: 300px;
    overflow-y: scroll;
    background-color: #fff;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,0.0600);
    box-sizing: border-box;
    .result-item {
    width: 100%;
    cursor: pointer;
    border-bottom: 2px solid #eee;
    padding: 10px 12px;
    .area-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        height: 20px;
        color: rgba(0, 0, 0, 0.65);
        font-size: 14px;
        line-height: 20px;
    }
    .area-address {
        color: rgba(0, 0, 0, 0.4500);
        font-size: 12px;
        line-height: 18px;
    }
    }
}
</style>

4.效果

5.注意事项

此组件封装依赖element ui 的弹窗组件,和input输入框组件。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的 Vue 接入高德地图选点的示例: 1. 在 index.html 中引入高德地图的 js 文件 ``` <script src="//webapi.amap.com/maps?v=1.4.10&key=your-amap-key"></script> ``` 2. 在 App.vue 中创建地图容器和初始化地图 ``` <template> <div id="map-container"></div> </template> <script> export default { mounted() { // 创建地图容器 const map = new AMap.Map("map-container", { zoom: 10 }); // 初始化地图 AMap.plugin("AMap.Geolocation", () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, // 是否使用高精度定位,默认:true timeout: 10000, // 超过10秒后停止定位,默认:5s buttonPosition: "RB", // 定位按钮的停靠位置 zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点 }); map.addControl(geolocation); geolocation.getCurrentPosition(); }); } }; </script> ``` 3. 添加选点功能 ``` <template> <div> <div id="map-container"></div> <div> <button @click="choosePoint">选点</button> <span>经度: {{ location.lng }}</span> <span>纬度: {{ location.lat }}</span> </div> </div> </template> <script> export default { data() { return { location: {} // 保存选定的经纬度 }; }, mounted() { const map = new AMap.Map("map-container", { zoom: 10 }); AMap.plugin("AMap.Geolocation", () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, timeout: 10000, buttonPosition: "RB", zoomToAccuracy: true }); map.addControl(geolocation); geolocation.getCurrentPosition(); }); }, methods: { choosePoint() { // 定义选点插件 const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, timeout: 10000, buttonPosition: "RB", zoomToAccuracy: true }); // 打开选点插件 map.addControl(geolocation); geolocation.getCurrentPosition(); // 监听选点事件 AMap.event.addListener(geolocation, "complete", result => { this.location.lng = result.position.lng; this.location.lat = result.position.lat; }); } } }; </script> ``` 希望这个示例对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值