关于从地图上获取经纬度

需求:点击“选择位置”,弹出如第二张图所示的位置选择框,引入地图,在地图中获取位置(经纬度)后,点击“确定”,更新到位置输入框中,文本格式为“经度,纬度”

在这里插入图片描述
在这里插入图片描述

将弹框封装了一个组件

map-dialog.vue
一定要给地图容器设置宽高

<template>
  <el-dialog
    title="位置"
    :visible.sync="dialogMapVisible"
    :close-on-click-modal="false"
    append-to-body
    width="60%"
  >
    <div style="margin-bottom: 10px">经度:{{ longitude }},纬度:{{ latitude }}</div>
    <div id="map" />
    <div style="margin-top: 10px; color: red">提示:拖动图标更新位置</div>
    <div slot="footer">
      <el-button @click="dialogMapVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
	export default {
		props: {
			positon: {
				type: String,
				default: '',
			}
		},
		data() {
			return {
				dialogMapVisible: false,
				map: null,
				mk: '',
				latitude: '',
				longitude: '',
			}
		},
		watch: {
			dialogMapVisible(val) {
				if (val) {
					this.initMap()
				}
			}
		},
		methods: {
			show() {
				this.dialogMapVisible = true
			},
			handleConfirm() {
		      this.dialogMapVisible = false
		      this.$emit('updatePosition', `${this.longitude},${this.latitude}`)
		    },
		}
		
	}
</script>
<style lang="scss" scoped>
    #map {
        width: 100%;
        height: 500px;
    }
</style>

父组件中引用

position为位置输入框的数据绑定

import mapDialog from './map-dialog.vue'

<map-dialog ref="mapDialog" :position="position" @updatePosition="updatePosition" />

// 点击“选择位置”
this.$refs.mapDialog.show()
// 更新位置
updatePosition(postion) {
	this.positon = position
}

两种地图实现: 百度地图和高德地图

百度地图实现

  1. public/index.html中引入
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的key"></script>
  1. methods中的方法
initMap() {
	const that = this
	that.$nextTick(() => {
		that.map = new BMap.Map('map')
		const point = new BMap.Point(116.404, 39.915)
		that.map.centerAndZoom(point, 12)
		that.map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放

		if (that.position) {
			const lng = that.position.split(',')[0]
			const lat = that.position.split(',')[1]
			that.handleMarker(new BMap.Point(lng, lat))
			that.longitude = lng
			that.latitude = lat
		} else {
			that.getLocation()
		}
	})
},
getLocation() {
	const that = this
	const geolocation = new BMap.Geolocation()
	geolocation.getCurrentPosition(function (res) {
		if(this.getStatus() == BMAP_STATUS_SUCCESS) {
			that.handleMarker(res.point)
			const myGeo = new BMap.Geocoder()
			myGeo.getLocation(new BMap.Point(res.point.lng, res.point.lat), (result) => {
				if (result) {
					that.latitude = result.point.lat
					that.longtitude = result.point.lng
				}
			})
		} else {
			console.log(`failed${this.getStatus()}`)
		}
	})
},
handleMarker(point) {
	const that = this
	that.mk = new BMap.Marker(point)
	that.map.addOverlay(that.mk)
	that.mk.enableDragging() // 可拖拽
	that.mk.addEventListener('dragend', (e) => {
		that.latitude = e.point.lat
		that.longitude = e.point.lng
	})
	that.map.panTo(point)
}

高德地图实现

  1. 安装高德地图加载器
npm i @amap/amap-jsapi-loader -S
  1. 引入加载器,设置安全密钥
import AMapLoader from '@amap/amap-jsapi-loader'

window._AMapSecurityConfig = {
  securityJsCode: '你的密钥',
}
  1. methods中的方法
initMap() {
	const that = this
	AMapLoader.load({
		key: '你的key',
		version: '2.0',
		plugins: [],
	}).then((AMap) => {
		that.map = new AMap.Map('map', {
			viewMode: '2D',
			zoom: 12,
			center: [116.404, 39.915],
          	resizeEnable: true,
		})
		
		if (that.position) {
			const lng = that.position.split(',')[0]
			const lat = that.position.split(',')[1]
			that.handleMarker(lng, lat)
			that.longitude = lng
			that.latitude = lat
		} else {
			that.getLocation()
		}
	})
},
getLocation() {
	const that = this
	AMap.plugin('AMap.Geolocation', () => {
		const geolocation = new AMap.Geolocation({
			enableHighAccuracy: false, // 是否使用高精度定位,默认:true
	        timeout: 10000, // 超过10秒后停止定位,默认:5s
	        zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
		})
		// 浏览器获取不道精准定位,所以就使用getCityInfo
		geolocation.getCityInfo((status, result) => {
			if (status === 'complete') {
	            const lng = result.position[0]
	            const lat = result.position[1]
	            that.handleMarker(lng, lat)
	            that.latitude = lat
	            that.longitude = lng
	          } else {
	            console.log('定位失败')
	          }
		})
	})
},
handleMarker(lng, lat) {
	const that = this
	that.mk = new AMap.Mrker({
		icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        position: [lng, lat],
        anchor: 'bottom-center',
        title: '拖动图标移动位置',
        draggable: true,
	})
	that.map.add(that.mk)
	that.map.setFitView()
	// 绑定拖拽事件
    that.mk.on('dragend', (e) => {
      that.latitude = e.lnglat.lat
      that.longitude = e.lnglat.lng
    })
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值