使用腾讯位置服务获取位置及设置地图点标记文本标记demo

52 篇文章 0 订阅

需要先创建应用和Key,去创建:https://lbs.qq.com/dev/console/application/mine

腾讯位置服务使用:
地图组件获取位置(开发指南:https://lbs.qq.com/webApi/component/componentGuide/componentGeolocation)
引入Javascript API GL初始化地图及设置点标记文本标记(开发指南:https://lbs.qq.com/webApi/javascriptGL/glGuide/glOverview)
demo代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=750, user-scalable=no">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-title" content="">
<title>腾讯地图test</title>
<style>
@charset "utf-8";
*{ margin:0px; padding:0px; box-sizing:border-box; -webkit-tap-highlight-color:rgba(0,0,0,0); cursor:pointer;}
html{ max-width:750px; margin:0 auto;}
body{ font-family:"PingFangSC-Regular","STHeitiSC-Light","微软雅黑","Microsoft YaHei","sans-serif"; font-size:28px; line-height:1.6; color:#000;  background-color:#fff;
	-webkit-user-select:none;
					user-select:none;
	-webkit-touch-callout:none;
					touch-callout:none;
}
li{ list-style:none;}
i{ font-style:normal;}
a:link , a:visited , a:hover ,a:active{ text-decoration:none; color:#000;}
.cle:after{ content:""; display:block; height:0; clear:both;}
button , input , select , textarea{ font-family:"PingFangSC-Regular","STHeitiSC-Light","微软雅黑","Microsoft YaHei","sans-serif"; outline:none; border-radius:0; font-size:30px;
	-webkit-appearance:none;
					appearance:none;
}
input[type=checkbox] , input[type=radio]{ margin:0 5px;}
input::-webkit-outer-spin-button , input::-webkit-inner-spin-button{ margin:0; 
	-webkit-appearance:none !important;
					appearance:none !important;
}
input::-webkit-input-placeholder{ color:#ccc;}
.hide , [v-clock]{ display:none;}
img{ max-width: 100%; vertical-align:middle;}

body{
	--navheight:80px;
}

@-webkit-keyframes fadeToLeft{
	0%{ -webkit-transform:translateX(100%); opacity:0;}
	100%{ -webkit-transform:translateX(0); opacity:1;}
}
@keyframes fadeToLeft{
	0%{ transform:translateX(100%); opacity:0;}
	100%{ transform:translateX(0); opacity:1;}
}

.nav{ width: 100%; height: var(--navheight); background-color: #fff; position: fixed; left: 0; top: 0; /* z-index: 1; */
	box-shadow: 0 3px 10px rgba(0,0,0,.1);
	display: flex; justify-content: center; align-items: center;
}
.nav_li{ height: 100%; text-align: center; position: relative;
	flex: 1; display: flex; justify-content: center; align-items: center;
}
.nav_li.curr{ color: #29a49f; font-weight: bold;}
.nav_li:not(:first-child)::before{ content: ""; width: 2px; height: 48px; background-color: #29a49f; position: absolute; left: 0; top: 50%; margin-top: -24px;}
.map_show{ height: 100vh; padding-top: var(--navheight); position: relative; overflow: hidden;}
.map_show div , .map_show canvas{ z-index: auto !important;}
/* 列表显示 */
.map_show_list{ width: 100%; height: calc(100% - var(--navheight)); background-color: #fff; position: absolute; left: 0; top: var(--navheight);
	-webkit-animation: fadeToLeft .3s ease-out both;
					animation: fadeToLeft .3s ease-out both;
}
.map_show_list ul{ padding: 20px;}
</style>
</head>

<body>

<section id="app" v-clock>
	
	<div class="map_show">
		<!-- 定义地图显示容器 -->
		<div id="container" style="width:100%; height:100%"></div>
		
		<!-- 列表显示 -->
		<div v-show="showList" class="map_show_list">
			<ul>
				<!-- 列表 -->
				<li @click="goDetail(item.id,item.lat,item.lon)" v-for="item,index in mapList">
					{{item.title}}
				</li>
			</ul>
		</div>
	</div>
	
	<!-- 菜单 -->
	<div class="nav">
		<div @click="showList = false" class="nav_li" :class="showList ? '' : 'curr'">地图</div>
		<div @click="showList = true" class="nav_li" :class="showList ? 'curr' : ''">列表</div>
	</div>
	
</section>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

<!-- 获取位置信息 - 微信JS-SDK - wx.getLocation 请确认config的jsApiList参数包含了getLocation(获取定位测试 小数点后第4位开始会有浮动) -->
<!-- <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js" tppabs="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script> -->

<!-- 获取位置信息 - 腾讯位置服务-地图组件-前端定位组件:调用方式一(获取定位测试 PC端不稳定大约需要15秒的处理时间;安卓机需https环境,WIFI及4G皆成功;苹果机WIFI及4G皆成功;) -->
<script src="https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js"></script>
<!-- <script src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script> -->
<!-- 获取位置信息 - 腾讯位置服务-地图组件-前端定位组件:调用方式三(获取定位测试 PC失败;安卓机需https环境,WIFI及4G皆成功;苹果机WIFI成功但位置有偏差,4G失败;) -->
<!-- <script src="https://apis.map.qq.com/tools/geolocation/min?key=YOUR_KEY&referer=wxapp"></script> -->

<!--引入Javascript API GL,参数说明参见下文-->
<script src="https://map.qq.com/api/gljs?v=1.exp&key=YOUR_KEY"></script>

<script type="text/javascript">
var VM = new Vue({
	el:"#app",
	data:{
		map:null,
		center:null,
		
		showList:false,
		mapList:[],
	},
	created() {
	},
	mounted() {
		//定义地图中心点坐标
		this.center = new TMap.LatLng(31.820564,117.227313);
		// 地图初始化
		this.initMap();
		// 获取位置信息
		this.getLocation();
		// 获取列表数据
		this.getData();
	},
	watch() {
	},
	methods:{
		// 获取位置信息 - 微信JS-SDK - wx.getLocation 请确认config的jsApiList参数包含了getLocation(获取定位测试 小数点后第4位开始会有浮动)
		// getLocation(){
		// 	wx.ready(function(){
		// 		console.log('获取定位中...');
		// 		wx.getLocation({
		// 			type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
		// 			success: function (res) {
		// 				console.log(res);
		// 				alert('定位成功,纬度' + res.latitude);
		// 				alert('定位成功,经度' + res.longitude);
		// 				// var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
		// 				// var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
		// 				// var speed = res.speed; // 速度,以米/每秒计
		// 				// var accuracy = res.accuracy; // 位置精度
		// 				// 重置地图中心点坐标
		// 				_this.map.setCenter(new TMap.LatLng(res.latitude,res.longitude));
		// 			}
		// 		});
		// 	});
		// },
		
		// 获取位置信息 - 腾讯位置服务-地图组件-前端定位组件
		getLocation(){
			let _this = this;
			
			console.log('获取定位中...');
			
			// 获取位置信息 - 腾讯位置服务-地图组件-前端定位组件:调用方式一(获取定位测试 PC端不稳定大约需要15秒的处理时间;安卓机需https环境,WIFI及4G皆成功;苹果机WIFI及4G皆成功;)
			var geolocation = new qq.maps.Geolocation('YOUR_KEY', 'wxapp');
			// 获取位置信息 - 腾讯位置服务-地图组件-前端定位组件:调用方式三(获取定位测试 PC失败;安卓机需https环境,WIFI及4G皆成功;苹果机WIFI成功但位置有偏差,4G失败;)
			// var geolocation = new qq.maps.Geolocation();
			
			var getNumber = 0;
			geolocation.getLocation(showPosition, showErr, {timeout: 5000});
			function showPosition(position) {
				console.log(getNumber,'定位成功');
				// var locationData = JSON.stringify(position, null, 4);
				var locationData = position;
				console.log(locationData);
				alert('定位成功,纬度' + locationData.lat);
				alert('定位成功,经度' + locationData.lng);
				// 重置地图中心点坐标
				_this.map.setCenter(new TMap.LatLng(locationData.lat,locationData.lng));
			};
			function showErr() {
				console.log(getNumber,'定位失败');
				if(getNumber >= 2){
					alert('友情提示:定位失败');
				}else{
					getNumber++;
					geolocation.getLocation(showPosition, showErr, {timeout: 5000});
				}
			};
		},
		
		//
		
		//地图初始化函数,本例取名为init,开发者可根据实际情况定义
		initMap() {
				let _this = this;
				//定义map变量,调用 TMap.Map() 构造函数创建地图
				_this.map = new TMap.Map(document.getElementById('container'), {
						center: _this.center, //设置地图中心点坐标
						zoom: 13,   //设置地图缩放级别3-20
						pitch: 40,  //设置俯仰角
						// rotation: 45    //设置地图旋转角度
						scale: 1.5
				});
				
				console.log(_this.map.getCenter());
		},
		
		//
		
		// 设置点标记 和 文字标记
		setMapMultiMarkerAndMultiLabel(styles,geometries,geometries2){
			let _this = this;
			
			//点标记 创建并初始化MultiMarker
			var markerLayer = new TMap.MultiMarker({
				map: _this.map,  //指定地图容器
				//样式定义
				styles: styles,
				// styles: {
				// 	//创建一个styleId为"myStyle"的样式(styles的子属性名即为styleId)
				// 	"myStyle": new TMap.MarkerStyle({ 
				// 		"width": 24, // 点标记样式宽度(像素)
				// 		"height": 24, // 点标记样式高度(像素)
				// 		"src": 'curr.png',  //图片路径
				// 		//焦点在图片中的像素位置,一般大头针类似形式的图片以针尖位置做为焦点,圆形点以圆心位置为焦点
				// 		"anchor": { x: 12, y: 12 }  
				// 	}) 
				// },
				//点标记 数据数组
				geometries: geometries,
				// geometries: [
				// 	{
				// 		"id": "1", //点标记唯一标识,后续如果有删除、修改位置等操作,都需要此id
				// 		"styleId": 'myStyle',  //指定样式id
				// 		"position": _this.center,  //点标记坐标位置
				// 		"properties": { //自定义属性
				// 			"title": "安徽省合肥市蜀山区科学大道116号5F创业园"
				// 		}
				// 	},
				// ]
			});
			// 点击事件
			markerLayer.on("click",(e)=>{
				// console.log(e);
				// console.log(e.latLng);
				// console.log(e.geometry);
				// console.log(e.geometry.id,e.latLng.lat,e.latLng.lng);
				console.log(e.geometry.id,e.geometry.position.lat,e.geometry.position.lng);
				// _this.goDetail(e.geometry.id,e.geometry.position.lat,e.geometry.position.lng);
				console.log(e.geometry.id,e.geometry.properties.lat,e.geometry.properties.lon);
				_this.goDetail(e.geometry.id,e.geometry.properties.lat,e.geometry.properties.lon);
			})
			
			//文字标记 初始化label
			var label = new TMap.MultiLabel({
				id: 'label-layer',
				map: _this.map, //设置折线图层显示到哪个地图实例中
				//文字标记样式
				styles: {
					'label': new TMap.LabelStyle({
						'color': '#ff0000', //颜色属性
						'size': 18, //文字大小属性
						// 'offset': { x: 0, y: 0 }, //文字偏移属性单位为像素
						'offset': { x: 0, y: 12 }, //文字偏移属性单位为像素
						'angle': 0, //文字旋转属性
						'alignment': 'center', //文字水平对齐属性
						'verticalAlignment': 'middle' //文字垂直对齐属性
					})
				},
				//文字标记数据
				geometries: geometries2,
				// geometries: [{
				// 	'id': 'label_1', //点图形数据的标志信息
				// 	'styleId': 'label', //样式id
				// 	'position': center, //标注点位置
				// 	'content': '腾讯北京总部', //标注文本
				// }]
			});
			// 点击事件
			label.on("click",(e)=>{
				console.log(e.geometry.id,e.geometry.position.lat,e.geometry.position.lng);
				_this.goDetail(e.geometry.id,e.geometry.position.lat,e.geometry.position.lng);
			})
		},
		
		//
		
		// 跳转详情页
		goDetail(id,lat,lon){
			console.log(id,lat,lon);
			if(confirm('您确认跳转至些详情页吗?')){
				console.log('确认跳转');
			}
		},
		
		//
		
		// 获取列表数据
		getData(){
			let _this = this;
			
			/* test */
			var res = {
				"status": 1,
				"list": [
					{
						"id": "MDAwMDAwMDAwMH-Je5h_jHqs", //id
						"markImg": "https://imgsrc.baidu.com/forum/pic/item/aa64034f78f0f736a4a890f80955b319eac413f0.jpg", //标点图
						"lon": "117.224802", //经度
						"lat": "31.811615", //纬度
						"title": "天鹅湖体育公园", //标题
					},
					{
						"id": "MDAwMDAwMDAwMH-Je5h_jHpi",
						"markImg": "https://imgsrc.baidu.com/forum/pic/item/aa64034f78f0f736a4a890f80955b319eac413f0.jpg",
						"lon": "117.232985",
						"lat": "31.818521",
						"title": "银泰城",
					}
				],
			}
			/* test */
			
			// AJAX获取定位点的列表数据 START
				console.log(res);
				_this.mapList = res.list;
				
				let styles = {} , geometries = [] , geometries2 = [];
				_this.mapList.forEach((item,index)=>{
					// console.log(item,index);
					//点标记 创建一个styleId为styles["styles" + index]的样式(styles的子属性名即为styleId)
					styles["styles" + index] = new TMap.MarkerStyle({
						"width": 36, // 点标记样式宽度(像素)
						"height": 36, // 点标记样式高度(像素)
						"src": item.markImg,  //图片路径
						//焦点在图片中的像素位置,一般大头针类似形式的图片以针尖位置做为焦点,圆形点以圆心位置为焦点
						// "anchor": { x: 12, y: 12 },
						"anchor": { x: 12, y: 36 },
					})
					
					//点标记 数据数组
					geometries[index] = {
						"id": item.id, //点标记唯一标识,后续如果有删除、修改位置等操作,都需要此id
						"styleId": "styles" + index,  //指定样式id
						"position":  new TMap.LatLng(item.lat,item.lon),  //点标记坐标位置
						"properties": { //自定义属性
							"title": item.title,
							"lat":item.lat,
							"lon":item.lon,
						}
					}
					
					//文字标记 数据数组
					geometries2[index] = {
						'id': item.id, //点图形数据的标志信息
						'styleId': 'label', //样式id
						'position':  new TMap.LatLng(item.lat,item.lon), //标注点位置
						'content': item.title, //标注文本
					}
					
					// //设置infoWindow 包含图文信息窗
					// var infoWindow = [];
					// infoWindow[index] = new TMap.InfoWindow({
					// 		map: _this.map,
					// 		position:  new TMap.LatLng(item.lat,item.lon),
					// 		content: "<div><img src='" + item.markImg + "'><p>" + item.title + "</p></div>"
					// });
					// // 点击事件
					// infoWindow[index].on("closeclick",(e)=>{
					// // infoWindow[index].on("click",(e)=>{
					// 	// console.log(e)
					// 	setTimeout(()=>{
					// 		infoWindow[index].open();
					// 	},10)
					// })
				})
				console.log(styles);
				console.log(geometries);
				console.log(geometries2);
				
				_this.setMapMultiMarkerAndMultiLabel(styles,geometries,geometries2);
			// AJAX获取定位点的列表数据 START
		}
		
	}
})
</script>
</body>
</html>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是详细的步骤: 1. 在 HTML 中地图容器和标记容器: ```html <template> <div class="map-container"> <div class="map" ref="map"></div> <div class="marker" ref="marker"></div> </div> </template> ``` 2. 在 `setup()` 函数中引入腾讯地图的 API 和样式文件,并创建地图标记: ```javascript import { onMounted, ref } from "vue"; export default { setup() { // 引入腾讯地图 API 和样式文件 const script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://map.qq.com/api/js?v=2.exp&key=YOUR_KEY_HERE"; script.onload = () => { // 创建地图标记 const map = new qq.maps.Map(document.getElementById("map"), { center: new qq.maps.LatLng(39.916527, 116.397128), zoom: 13, }); const marker = new qq.maps.Marker({ position: map.getCenter(), draggable: true, map: map, }); // 监听标记拖动结束事件 qq.maps.event.addListener(marker, "dragend", function (event) { // 获取标记位置的经纬度信息 const latLng = marker.getPosition(); console.log("经度:" + latLng.getLng() + ",纬度:" + latLng.getLat()); }); }; document.head.appendChild(script); return {}; }, }; ``` 3. 在 `mounted()` 函数中获取地图标记容器的 DOM 节: ```javascript import { onMounted, ref } from "vue"; export default { setup() { // ... onMounted(() => { // 获取地图标记容器的 DOM 节 const mapContainer = document.getElementById("map"); const markerContainer = document.getElementById("marker"); // 设置地图标记容器的宽度和高度 mapContainer.style.width = "100%"; mapContainer.style.height = "400px"; markerContainer.style.width = "32px"; markerContainer.style.height = "32px"; // 将标记容器作为标记的图标 marker.setIcon( new qq.maps.MarkerImage( "http://open.map.qq.com/doc/img/n_marker.png", null, null, null, new qq.maps.Size(32, 32) ) ); marker.set("offset", new qq.maps.Size(0, 0)); marker.set("iconAnchor", new qq.maps.Point(16, 16)); marker.set("shadow", new qq.maps.MarkerImage(null, null, null, null, new qq.maps.Size(0, 0))); markerContainer.appendChild(marker.get("container")); }); return {}; }, }; ``` 4. 最后在 CSS 中设置地图容器的样式: ```css .map-container { position: relative; } .map { position: relative; z-index: 1; } .marker { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 2; } ``` 这样就完成了使用腾讯地图拖动标记获取经纬度的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值