vue3 高德地图关键词搜索获取经纬度

html 

  <el-tag v-if='isSave' size="small" style="cursor:pointer;margin-left:20px;" @click="open()">点击选取</el-tag>
<el-dialog
          class="dialog companygoodsLog"
          v-model="visible"
          :close-on-click-modal="false"
          :draggable="true"
          :show-close="false"
          title="位置选择"
          destroy-on-close
          style="border-radius: 4px;background-color: #ffffff"
          top="100px"
          width="80%">
          <div style="height:40px;width:100%;display: flex;align-items: center;">
              <el-select
                  v-model="areaValue"
                  filterable
                  style='width:350px'
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @change="currentSelect"
              >
                      <el-option
                        v-for="item in areaList"
                        :key="item.id"
                        :label="item.name"
                        :value="item"
                        class="one-text"
                    >
                      <span style="float: left">{{ item.name }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{item.district}}{{item.address}}</span>
                  </el-option>
              </el-select>
          </div>
          <div id="container" style="height:500px;width:100%;margin-top:10px;"></div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="visible = false"><span style="color: #5E5E5E">关闭</span></el-button>
              <el-button color="#68964C" @click="confirmData">
              确定
              </el-button>
            </span>
          </template>
      </el-dialog>

 ts:

<script setup lang="ts">
import { reactive,ref,onMounted, onUnmounted,watch  } from 'vue'
import AMapLoader from "@amap/amap-jsapi-loader";

const dialogMap = ref(false)
const mapContainer = ref(null);
const visible:any = ref(false)
const areaList:any =ref([])
const areaValue = ref('')
let map:any = null
const loading:any = ref(false)
const checkedForm:any = ref()
let AutoComplete:any = null
let aMap:any = null
let geoCoder:any = null
const initMap = () => {
    AMapLoader.load({
    key: "高德key",
    version: "2.0", 
    plugins: ["AMap.Geocoder", "AMap.AutoComplete"], 
  }).then((AMap:any) => {
      aMap = AMap
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: [116.397428, 39.90923], // 初始化地图中心点位置
      });
      AutoComplete = new AMap.AutoComplete({
        city:'全国',
      });
      geoCoder = new AMap.Geocoder({
        city: "010", //城市设为北京,默认:“全国”
        radius: 1000, //范围,默认:500
      });
      map.on('click',(e:any)=>{
        addmark(e.lnglat.getLng(),e.lnglat.getLat(),AMap)
      })
    })
    .catch((e) => {
      console.log(e);
    });
}
let marker:any = null
const addmark = (lat:any,lng:any,AMap:any) => {
    marker && removeMarker()
    marker = new AMap.Marker({
            position: new AMap.LngLat(lat, lng),
            title: '北京',
            zoom: 13
    });
    checkedForm.value = {
        lat:lng,
        lng:lat,
    }
    map.add(marker);
    map.setCenter([lat, lng],'',500);
}
 
const removeMarker = () => {
    map.remove(marker)
}
 
const remoteMethod = (searchValue:any) => {
    if (searchValue !== "") {
      setTimeout(() => {
          AutoComplete.search(searchValue, (status:any, result:any) => {
              console.log(result,status)
              if(result.tips?.length){
                  areaList.value = result?.tips
              }
          });
      }, 200);
    } else {
    
    }
}
 
const currentSelect = (val:any) => {
    checkedForm.value = {
        lat:val.location?.lat,
        lng:val.location?.lng,
    }
    console.log(val)
    areaValue.value = val.name
    addmark(val.location?.lng,val.location?.lat,aMap)
    map.setCenter([val.location?.lng,val.location?.lat],'',500);
}
 
const confirmData = () => {
    if(!checkedForm.value?.lat || !checkedForm.value?.lng){
        return ElMessage.error('请选择地址')
    }else{
      console.log(checkedForm.value)
      visible.value = false
      areaValue.value = ''
      map?.destroy();
      list.longitude = checkedForm.value.lng
      list.latitude = checkedForm.value.lat
    }
}
const open = () => {
    initMap()
    visible.value = true
}
 
defineExpose({
    open
})
onUnmounted(() => {
  map?.destroy();
});
</script>

根据经纬度展示地图标点 

<el-button v-if="list.longitude" type="primary"  style="margin-bottom: 20px;"@click="showMapDialog()">点击查看位置</el-button>
<el-dialog v-model="dialogMap" title="位置信息" width="900px">
            <div ref="mapContainer" id="container" style="height:500px;width:100%;margin-top:10px;"></div>
        </el-dialog>
<script setup>
import { reactive, ref, onMounted, toRefs, watch } from 'vue'
import AMapLoader from "@amap/amap-jsapi-loader";
const dialogVisible = ref(false)
const dialogMap = ref(false)
const mapContainer = ref(null);
const props = defineProps({
    isShow15: {
        type: Boolean,
        default: false,
    },
    list:{
        default:{}
    }
});
const emits = defineEmits(['close15'])
const closeDialog = () => {
    emits('close15', false)
}
const mapList = ref([])
watch(() => props.isShow15, (val) => {
    // console.log(val)
    dialogVisible.value = val
}, { immediate: true })
watch(() => props.list, (val) => {
    mapList.value = val
}, { immediate: true })
const showMapDialog = async () => {
    dialogMap.value = true;
    initMap();
};
let map = null
let aMap = null
let AutoComplete = null
let geoCoder = null
let marker = null;
const initMap = () => {
    AMapLoader.load({
    key: "高德地图key",
    version: "2.0", 
    plugins: ["AMap.Geocoder", "AMap.AutoComplete"], 
  }).then((AMap) => {
      aMap = AMap
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "2D", // 是否为3D地图模式
        zoom: 21, // 初始化地图级别
        center: [parseFloat(mapList.value.longitude), parseFloat(mapList.value.latitude)], // 初始化地图中心点位置
      });
      AutoComplete = new AMap.AutoComplete({
        city:'全国',
      });
      geoCoder = new AMap.Geocoder({
        city: "010", //城市设为北京,默认:“全国”
        radius: 1000, //范围,默认:500
      });
      geoCoder = new AMap.Geocoder({
        city: "全国", //城市设为北京,默认:“全国”
        radius: 1000, //范围,默认:500
      })
      marker = new aMap.Marker({
            position: [parseFloat(mapList.value.longitude), parseFloat(mapList.value.latitude)],
            map: map,
        });
    })
    .catch((e) => {
      console.log(e);
    });
}
</script>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现在vue中点击高德地图获取经纬度和详细地址,可以按照以下步骤进行: 1. 在vue项目中安装 `vue-amap` 插件。可以使用npm安装,命令如下: ``` npm install vue-amap --save ``` 2. 在 `main.js` 中引入 `vue-amap` 并进行初始化配置。 ```javascript import VueAMap from 'vue-amap'; Vue.use(VueAMap); VueAMap.initAMapApiLoader({ key: 'your amap key', plugin: ['AMap.Geocoder'] }); ``` 其中 `your amap key` 是你的高德地图开发者Key,需要在高德开放平台上申请。 3. 在组件中引入 `Amap` 组件,并在 `mounted` 钩子函数中进行地图初始化以及监听地图点击事件。 ```vue <template> <div> <div id="map" style="height: 500px;"></div> </div> </template> <script> export default { data() { return { map: null, geocoder: null, marker: null, address: '', lnglat: null } }, mounted() { this.initMap(); this.initGeocoder(); this.addMapClickEvent(); }, methods: { initMap() { this.map = new AMap.Map('map', { zoom: 13, center: [116.397428, 39.90923] }); }, initGeocoder() { this.geocoder = new AMap.Geocoder({ city: "北京" }); }, addMapClickEvent() { let self = this; this.map.on('click', function(e) { self.lnglat = e.lnglat; self.getAddressByLngLat(); self.addMarker(); }); }, getAddressByLngLat() { let self = this; this.geocoder.getAddress(this.lnglat, function(status, result) { if (status === 'complete' && result.regeocode) { self.address = result.regeocode.formattedAddress; } }); }, addMarker() { if (this.marker) { this.map.remove(this.marker); } this.marker = new AMap.Marker({ position: this.lnglat, }); this.map.add(this.marker); } } } </script> ``` 4. 在 `data` 中定义需要用到的变量,如 `map` 表示地图对象、 `geocoder` 表示逆地址解析对象、 `marker` 表示标记点对象、 `address` 表示详细地址、 `lnglat` 表示经纬度。 5. 在 `mounted` 钩子函数中,先调用 `initMap` 方法初始化地图对象,然后调用 `initGeocoder` 方法初始化逆地址解析对象,最后调用 `addMapClickEvent` 方法监听地图点击事件。 6. 在 `addMapClickEvent` 方法中,使用 `map.on('click', function(e) {...})` 监听地图点击事件,并在回调函数中获取点击位置的经纬度并保存到 `lnglat` 变量中,然后调用 `getAddressByLngLat` 方法通过经纬度获取详细地址,并调用 `addMarker` 方法在地图上添加标记点。 7. 在 `getAddressByLngLat` 方法中,调用逆地址解析对象的 `getAddress` 方法,根据经纬度获取详细地址,并将地址保存到 `address` 变量中。 8. 在 `addMarker` 方法中,先判断是否已有标记点,如果有则先移除旧的标记点,然后创建新的标记点并添加到地图上。 9. 最后,在模板中使用 `id="map"` 定义地图容器,并添加样式 `style="height: 500px;"`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值