首先 安装依赖
npm i @amap/amap-jsapi-loader --save
html(设置一个容器)点击位置控制台可以打印到数据 如果想要回显到input 只需在input内绑定v-modal即可
<template> <div> <input style="width: 80%; height: 30px" v-model="mapData.keyword" @keydown.enter="search" /> <button @click="search">搜索</button> <div id="container" class="map" style="height: 400px; border-radius: 5px"></div> </div> </template>
script
<script setup> //引入 import {onMounted,ref,reactive} from 'vue'; import AMapLoader from '@amap/amap-jsapi-loader'; const map = ref(null); const mapData = reactive({ map: {}, keyword: '', selectedLocation: {}, selectedAddress: '', }); onMounted(() => { window._AMapSecurityConfig = { securityJsCode: '', // 密钥 }; AMapLoader.load({ key: '',//key值 version: '1.4.15', plugins: ['AMap.PlaceSearch'], }) .then((AMap) => { const mapInstance = new AMap.Map('container', { viewMode: '2D', zoom: 11, center: [113.984358, 35.288668], layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()], }); mapInstance.on('click', (e) => { //点击位置获取经纬度 const lng = e.lnglat.getLng(); const lat = e.lnglat.getLat(); // 触发父组件传递的回调函数 // this.$emit('map-click', lng, lat); console.log(lng, lat); }); mapData.map = mapInstance; }) .catch((e) => { console.log(e); }); }); const search = () => { console.log(mapData.keyword); if (mapData.keyword) { AMapLoader.load({ key: '',//key值 version: '1.4.15', plugins: ['AMap.PlaceSearch'], }) .then((AMap) => { const placeSearch = new AMap.PlaceSearch({ city: '', map: mapData.map, }); console.log(mapData.keyword); placeSearch.search(mapData.keyword, (status, result) => { console.log(status, result.info); if (status === 'complete' && result.info === 'OK') { const pois = result.poiList.pois; if (pois.length > 0) { const { location } = pois[0]; mapData.map.setCenter(location); } } else { console.log('搜索失败或无结果'); } }); }) .catch((e) => { console.log(e); }); } }; </script>
style
<style scoped> .map { width: 100%; } </style>
效果:
如果想要更改地图的图层颜色 就把这个layers更改为以下:
layers: [ new AMap.TileLayer.RoadNet(), new AMap.TileLayer.WMS({ url: 'https://ahocevar.com/geoserver/wms', // wms服务的url地址 blend: false, // 地图级别切换时,不同级别的图片是否进行混合 tileSize: 512, // 加载WMS图层服务时,图片的分片大小 params: { 'LAYERS': 'topp:states', VERSION: '1.3.0' } // OGC标准的WMS地图服务的GetMap接口的参数 }) ],
效果