100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > vue3 简单封装GoogleMap组件

vue3 简单封装GoogleMap组件

时间:2021-03-24 15:47:19

相关推荐

vue3 简单封装GoogleMap组件

关于支持vue3的GoogleMap,暂时推荐两种

vue3-google-map

vue3 google maps

大家有较好的推荐欢迎交流

我这里选用的第二种

npm install -S @fawmi/vue-google-maps

然后再main中引入

// google-mapimport VueGoogleMaps from '@fawmi/vue-google-maps'app.use(VueGoogleMaps, {load: {key: 你的Google map key// language: 'de',}})

新建一个xxx.vue的模块

<div id="googleMap" class="mapCont"><GMapMap ref="mapRef" :center="center" :zoom="15"><GMapMarker v-for="(item, index) in markerOptions" :key="index" :position="item.position" /></GMapMap></div>

GMapMap 为地图,GMapMarker为标记,其他需求看文档就好了

const center = reactive({ lat: 51.093048, lng: 6.84212 })const mapKey = settings.googleMapKeyconst markerOptions = reactive([{position: {lat: 51.093048,lng: 6.84212}}])

设置地图中心和坐标点

在旁边随便加个搜索框,搜索并设为中心,搜索这里是使用的geocode

const reqSearch = () => {axios.get('/maps/api/geocode/json?address=' + data.searchVal + '&key=' + mapKey).then((res) => {console.log('res', res)if (res.data.status == 'OK') {center.lat = res.data.results[0].geometry.location.latcenter.lng = res.data.results[0].geometry.location.lngmarkerOptions.splice(0, 1, { position: { lat: center.lat, lng: center.lng } })axios.get(`/maps/api/geocode/json?&key=${mapKey}&latlng=${center.lat},${center.lng}`).then((res) => {console.log(res)if (res.data.status == 'OK') {addressParse.lat = res.data.results[0].geometry.location.lataddressParse.lng = res.data.results[0].geometry.location.lnglet sourceData = res.data.results.sort((a, b) => {return b.address_components.length - a.address_components.length})sourceData = sourceData[0].address_componentsaddressParse.address = res.data.results[0].formatted_addresssourceData.forEach((item) => {if (item.types[0] == 'country') {addressParse.nation = item.long_name}if (item.types[0] == 'administrative_area_level_1') {addressParse.Province = item.long_name}if (item.types[0] == 'administrative_area_level_2' || item.types[0] == 'locality') {addressParse.city = item.long_name}if (item.types[0] == 'postal_code') {addressParse.postal_code = item.long_name}})console.log(addressParse)} else {ElMessage.error('地址详情查询失败')}})} else {ElMessage.error('查询失败')}}).catch((err) => {console.log('err', err)ElMessage.error('查询失败')})}

我这里首先通过地址搜索,得到经纬度,然后通过经纬度取货去更详细的地址信息,英语不好文档看的太折磨了,大家有什么好办法欢迎交流

这是我最终需要的一些值

const addressParse = reactive({nation: '',Province: '',city: '',address: '',postal_code: '',lat: '',lng: ''})

在父组件使用

<googleMap ref="searchAddRef" @getLocal="getLocal" style="height: 100%; width: 100%" />import googleMap from '@c/googleMap/googleMap'

因为这里我用的是setup语法糖,需要来设置emit

const emit = defineEmits(['getLocal'])emit('getLocal', addressParse)

父组件接收

const getLocal = (addressParse) => {console.log(addressParse)}

完事(其实踩了好多坑)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。