vue3+ts 引入高德地图并使用地图选点和搜索

引入高德地图

npm i @amap/amap-jsapi-loader --save

 在index.html引入

<script type="text/javascript">
    window._AMapSecurityConfig = {
        securityJsCode: '', // 你的密钥
    }
</script>

创建map.vue组件 

<template>
  <div class="home">
    <div id="map-box"></div>
    <div class="btn">
      <el-button type="primary" @click="btnsubmit">确定</el-button>
    </div>
    <div class="info-box">
      <el-input
          v-model="keyword"
          placeholder="输入关键字搜索"
          style="width: 300px"
          @change="handleSearch"
      >
      </el-input>
      <div class="ul">
        <div class="li" v-for="item in data" :key="item.id" @click="handleSelect(item)">
          <div class="d-flex flex-column">
            <span style="margin-bottom: 6px">{{item.name}}</span>
            <span>地址:{{item.address}}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { shallowRef,defineEmits,defineComponent,ref, onBeforeUnmount } from 'vue';
import AMapLoader from "@amap/amap-jsapi-loader";

const map = shallowRef(null);
const keyword = ref('');
const addresstext = ref('')
const data = ref([]);
const coord = ref('');
const adcode = ref('')
let AMapObj, placeSearch, marker, geocoder;
const props = defineProps({
  form:{}
})
function initMap(){
  AMapLoader.load({
    key: '',  //设置您的key
    version: "2.0",
    plugins: ['AMap.ToolBar','AMap.Driving'],
    AMapUI: {
      version: "1.1",
      plugins: [],

    },
    Loca:{
      version: "2.0.0"
    },
  }).then((AMap)=>{
    // console.log(AMap);
    AMapObj = AMap;
    map.value = new AMap.Map("map-box",{
      viewMode:"3D",
      zoom:12,
      zooms:[2,22],
      center: [116.397256,39.908703],
    });

    map.value.on('click', onMapClick);
    AMap.plugin(
        ['AMap.ToolBar','AMap.Scale','AMap.Geolocation','AMap.PlaceSearch',
          'AMap.Geocoder','AMap.AutoComplete'],
        () => {
          // 缩放条
          const toolbar = new AMap.ToolBar();
          // 比例尺
          const scale = new AMap.Scale();
          // 定位
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位,默认:true
            timeout: 10000, // 超过10秒后停止定位,默认:5s
            position: 'RT', // 定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
            zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
          });
          geocoder = new AMap.Geocoder({
            city: '全国',
          });
          map.value.addControl(geolocation);
          map.value.addControl(toolbar);
          map.value.addControl(scale);
          placeSearch = new AMap.PlaceSearch({
            city: '全国',
            pageSize: 10, // 单页显示结果条数
            pageIndex: 1, // 页码
            citylimit: false, // 是否强制限制在设置的城市内搜索
            autoFitView: true,
          });
        });
    if(props.form){
      keyword.value=props.form.adress
      handleSearch(props.form.adress)
      let e={
        lnglat:{
          lng:props.form.longitude,
          lat: props.form.latitude
        }
      }
      onMapClick(e)
    }
  }).catch(e=>{
    console.log(e);
  })
}

// 搜索地图
function handleSearch(str) {
  placeSearch.search(str, (status, result) => {
    if (result && typeof result === 'object' && result.poiList) {
      const list = result.poiList.pois;
      list.forEach(item => {
        item.value = item.name;
        item.label = item.name;
      });
      data.value = list
    }
  });
}
// 点击地图
function onMapClick(e) {
  coord.value = e.lnglat.lng + ',' + e.lnglat.lat
  geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      // result为对应的地理位置详细信息
      keyword.value = result.regeocode.formattedAddress
      addresstext.value = result.regeocode.formattedAddress
      adcode.value = result.regeocode.addressComponent.adcode.slice(0,4)+'00'
    }
  })
  drawMarker(e.lnglat)
}
function onMapadcode (e){
  geocoder.getAddress([e.location.lng, e.location.lat], function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      // result为对应的地理位置详细信息
      adcode.value = result.regeocode.addressComponent.adcode.slice(0,4)+'00'
    }
  })
}
// 点击搜索项
function handleSelect(item) {
  drawMarker(item.location)
  onMapadcode(item)
  if (item.location != null) {
    coord.value = item.location.lng + ',' + item.location.lat
    keyword.value = item.name
    addresstext.value = item.address

  }
}
// 绘制地点marker
function drawMarker(location) {
  if (location == null) return
  let longitude = location.lng, latitude = location.lat
  if (marker) {
    marker.setMap(null);
  }
  marker = new AMapObj.Marker({
    position: new AMapObj.LngLat(longitude, latitude),
    anchor: 'bottom-center',
  });
  marker.on('click', () => {
    coord.value = location;
  })
  map.value.add(marker);
  map.value.setZoomAndCenter(16, [longitude, latitude]);
}
const emit = defineEmits(['btnAddress'])
function btnsubmit(){
  emit('btnAddress',coord.value,addresstext.value,adcode.value)
}
initMap();

</script>

<style lang="scss" scoped>
.home{
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
  position: relative;

  .info-box {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 300px;
    height: 100%;
    //background-color: #1f1f1f;
    display: flex;
    flex-direction: column;
  }
}
.ul{
  margin-top: 10px;
  height: 60%;
  overflow-y: scroll;
  .li{
    padding: 5px 10px;
    background: #FFFFFF;
    margin-bottom: 10px;
    min-height: 60px;
    .d-flex{
      background: #FFFFFF;
      color: #1f1f1f;
      display: flex;
      flex-direction: column;
    }
  }
}

#map-box{
  height: calc(100% - 30px);
  width: 100%;
  padding: 0px;
  margin: 0px;
}
.btn{
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

<style scoped>
:deep() .amap-logo {
  display: none !important;
}
:deep() .amap-copyright {
  display: none !important;
}
</style>

向父组件传值

emit('btnAddress',coord.value,addresstext.value,adcode.value)

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用高德地图实现模糊搜索定位,你需要先在项目中引入高德地图的 JavaScript API,并且需要获取高德地图的 API key。接下来,你可以使用 Autocomplete 插件实现模糊搜索,具体实现步骤如下: 1. 在 Vue 3 中安装高德地图的 JavaScript API。 ```bash npm install @amap/amap-jsapi-loader --save ``` 2. 在 main.ts 文件中引入高德地图的 JavaScript API,并在创建 Vue 实例之前加载 JavaScript API。 ```typescript import { createApp } from 'vue' import App from './App.vue' import AMapLoader from '@amap/amap-jsapi-loader' AMapLoader.load({ key: 'your_amap_api_key', version: '2.0', plugins: ['AMap.Autocomplete'] }).then(() => { createApp(App).mount('#app') }) ``` 3. 在组件中使用 Autocomplete 插件实现模糊搜索。 ```vue <template> <div> <input v-model="address" placeholder="请输入地址" /> <ul> <li v-for="suggestion in suggestions" :key="suggestion.id">{{ suggestion.name }}</li> </ul> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue' import AMapLoader from '@amap/amap-jsapi-loader' export default defineComponent({ name: 'AutoCompleteDemo', setup() { const address = ref('') const suggestions = ref([]) const search = async () => { const AMap = await AMapLoader.load({ key: 'your_amap_api_key', version: '2.0', plugins: ['AMap.Autocomplete'] }) const autoComplete = new AMap.Autocomplete({ city: '全国' }) autoComplete.search(address.value, (status, result) => { if (status === 'complete' && result.tips) { suggestions.value = result.tips } }) } return { address, suggestions, search } } }) </script> ``` 在这个例子中,我们使用了 ref 函数来创建了两个响应式变量 address 和 suggestions,分别用于存储输入的地址和搜索结果。我们还定义了一个 search 函数,在用户输入时触发,它会通过 AMapLoader.load() 方法加载 Autocomplete 插件,并使用 Autocomplete.search() 方法进行模糊搜索。当搜索完成时,Autocomplete.search() 的回调函数会返回搜索结果,我们将结果存储在 suggestions 变量中,并在页面中渲染出来。 注意,这里我们设置了 city 属性为全国,表示搜索范围为全国。你也可以根据需要修改为特定的城市或区域。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值