前段时间呢,由于工作原因研究了百度地图api的基本用法。百度地图用法点击查看
所以开始对地图产生了点兴趣,最近花了几个时间研究了下腾讯地图的基本使用。
只要是个cv程序员,快的话可能只要1个小时就能上手,慢的话最多一天就能学会。
百度地图VS腾讯地图(个人角度)
以下是我腾讯地图基本使用的笔记~
大致这些功能:
1.基础入门
2.地图显示控制
3.地图显示3D效果
4.地图事件-拾取坐标
5.默认的点标记
6.自定义点标记
7.添加marker
8.对marker添加点击事件
9.自定义样式
10.marker轨迹回放
11.基本点聚合
12.自定义点聚合样式
13.信息窗口
14.折线
15.个性化地图
16.计算直线距离
17.地址坐标转换
18.驾车路线规划
19.公交路线规划
20.下属行政区查询
腾讯地图官网
<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
<div id="container"></div>
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#container {
width: 100%;
height: 100%;
}
rotation:设置地图旋转角度
pitch:设置俯仰角度(0~45)
zoom:设置地图缩放级别
center:设置地图中心点坐标
viewMode:2D/3D 可定义2D的还是3D 的
<script type="text/javascript">
var center = new TMap.LatLng(39.984104, 116.307503);
//初始化地图
var map = new TMap.Map("container", {
rotation: 20,//设置地图旋转角度
pitch: 30, //设置俯仰角度(0~45)
zoom: 12,//设置地图缩放级别
center: center//设置地图中心点坐标
});
</script>
rotation:设置地图旋转角度
pitch:设置俯仰角度(0~45)
zoom:设置地图缩放级别
center:设置地图中心点坐标
viewMode:2D/3D 可定义2D的还是3D 的
//修改地图中心点
map.setCenter(new TMap.LatLng(lat,lng));
var centerLatLng=map.getCenter();
//定义事件处理方法
var clickHandler=function(evt){
var lat = evt.latLng.getLat().toFixed(6);
var lng = evt.latLng.getLng().toFixed(6);
console.log("您点击的的坐标是:"+ lat + "," + lng);
}
//Map实例创建后,通过on方法绑定点击事件
map.on("click",clickHandler)
//Map实例创建后,通过on方法绑定点击事件
map.on("click",clickHandler)
//通过off方法解绑点击事件
map.off("click",clickHandler);
var marker = new TMap.MultiMarker({
map: map,
styles: {
// 点标记样式
marker: new TMap.MarkerStyle({
width: 20, // 样式宽
height: 30, // 样式高
anchor: { x: 10, y: 30 }, // 描点位置
}),
},
geometries: [
// 点标记数据数组
{
// 标记位置(纬度,经度,高度)
position: center,
id: 'marker',
},
],
});
//创建并初始化MultiMarker
var markerLayer = new TMap.MultiMarker({
map: map, //指定地图容器
//样式定义
styles: {
//创建一个styleId为"myStyle"的样式(styles的子属性名即为styleId)
"myStyle": new TMap.MarkerStyle({
"width": 25, // 点标记样式宽度(像素)
"height": 35, // 点标记样式高度(像素)
"src": 'img/旗帜.png', //图片路径
//焦点在图片中的像素位置,一般大头针类似形式的图片以针尖位置做为焦点,圆形点以圆心位置为焦点
"anchor": { x: 16, y: 32 }
})
},
//点标记数据数组
geometries: [{
"id": "1", //点标记唯一标识,后续如果有删除、修改位置等操作,都需要此id
"styleId": 'myStyle', //指定样式id
"position": new TMap.LatLng(39.954104, 116.357503), //点标记坐标位置
"properties": {//自定义属性
"title": "marker1"
}
}, {//第二个点标记
"id": "2",
"styleId": 'marker',
"position": new TMap.LatLng(39.994104, 116.287503),
"properties": {
"title": "marker2"
}
}
]
});
//创建marker事件
var marker = null;
function createMarker() {
if (!marker) {
marker = new TMap.MultiMarker({
id: 'marker-layer',
map: map,
styles: {
"marker": new TMap.MarkerStyle({
"width": 25,
"height": 35,
"anchor": { x: 16, y: 32 },
"src": 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
})
},
geometries: [{
"id": 'demo',
"styleId": 'marker',
"position": new TMap.LatLng(39.984104, 116.307503),
"properties": {
"title": "marker"
}
}]
});
}
}
//移除marker事件
function removeMarker() {
if (markerLayer) {
markerLayer.setMap(null);
markerLayer = null;
}
}
//初始化marker图层
var markerLayer = new TMap.MultiMarker({
id: 'marker-layer',
map: map
});
//监听点击事件添加marker
map.on("click", (evt) => {
markerLayer.add({
position: evt.latLng
});
});
//监听回调函数(非匿名函数)
var eventClick = function (evt) {
markerID.innerHTML = "markerID:" + evt.geometry.id;
position.innerHTML = "当前marker位置:" + evt.geometry.position.toString();
}
function addClick() {
txt.innerHTML = "绑定点击事件";
//监听marker点击事件
marker.on("click", eventClick)
}
//更换marker样式方法
marker.setStyles({"marker": new TMap.MarkerStyle({
"width": 70,
"height": 70,
"src": 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerNew.png',
"opacity": 0.5
})})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>基本点聚合功能</title>
<style>
html,
body {
margin: 0;
padding: 0;
overflow: hidden;
height: 100%;
}
#mapContainer {
position: relative;
height: 100%;
width: 100%;
}
</style>
</head>
<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
<body onload="init()">
<div id='mapContainer'></div>
<script>
var map;
function init() {
var drawContainer = document.getElementById('mapContainer');
var center = new TMap.LatLng(39.984104, 116.307503);//设置中心点坐标
map = new TMap.Map(drawContainer, {
zoom: 9,
pitch: 40,
center: center,
draggable: true,
scrollable: true,
mapStyleId: "style 1"
});
// 创建点聚合实例
var markerCluster = new TMap.MarkerCluster({
id: 'cluster',
map: map,
enableDefaultStyle: true, // 启用默认样式
minimumClusterSize: 2, // 形成聚合簇的最小个数
geometries: [{ // 点数组
position: new TMap.LatLng(39.953416, 116.480945)
},
{
position: new TMap.LatLng(39.984104, 116.407503)
},
{
position: new TMap.LatLng(39.908802, 116.497502)
},
{
position: new TMap.LatLng(40.040417, 116.373514)
},
{
position: new TMap.LatLng(39.953416, 116.380945)
},
{
position: new TMap.LatLng(39.984104, 116.307503)
},
{
position: new TMap.LatLng(39.908802, 116.397502)
},
{
position: new TMap.LatLng(40.040417, 116.273514)
},
],
zoomOnClick: true, // 点击簇时放大至簇内点分离
gridSize: 60, // 聚合算法的可聚合距离
averageCenter: false, // 每个聚和簇的中心是否应该是聚类中所有标记的平均值
maxZoom: 10 // 采用聚合策略的最大缩放级别
});
}
</script>
</body>
</html>
//初始化infoWindow
var infoWindow = new TMap.InfoWindow({
map: map,
position: center, //设置信息框位置
content: 'Hello World!' //设置信息框内容
});
//设置infoWindow
var infoWindow = new TMap.InfoWindow({
map: map,
position: center,
content: "Hello World!
"
});
//初始化infoWindow
var infoWindow = new TMap.InfoWindow({
map: map,
position: new TMap.LatLng(39.984104, 116.307503),
offset: { x: 0, y: -32 } //设置信息窗相对position偏移像素
});
infoWindow.close();//初始关闭信息窗关闭
//监听标注点击事件
marker.on("click", function (evt) {
//设置infoWindow
infoWindow.open(); //打开信息窗
infoWindow.setPosition(evt.geometry.position);//设置信息窗位置
infoWindow.setContent(evt.geometry.position.toString());//设置信息窗内容
})
offset: { x: -3, y: -35 }, //向上偏移35像素坐标,向左偏移3像素坐标
infoWindowTwo = new TMap.InfoWindow({
map: map,
position: center,
zIndex: 10, //信息窗的z-index值
offset: { x: -3, y: -35 }, //向上偏移35像素坐标,向左偏移3像素坐标
content: '左上方偏移的infoWindow'
});
//创建 MultiPolyline
var polylineLayer = new TMap.MultiPolyline({
id: 'polyline-layer', //图层唯一标识
map: map,//绘制到目标地图
//折线样式定义
styles: {
'style_blue': new TMap.PolylineStyle({
'color': '#3777FF', //线填充色
'width': 6, //折线宽度
'borderWidth': 5, //边线宽度
'borderColor': '#FFF', //边线颜色
'lineCap': 'butt' //线端头方式
}),
'style_red': new TMap.PolylineStyle({
'color': '#CC0000', //线填充色
'width': 6, //折线宽度
'borderWidth': 5, //边线宽度
'borderColor': '#CCC', //边线颜色
'lineCap': 'round' //线端头方式
})
},
//折线数据定义
geometries: [
{//第1条线
'id': 'pl_1',//折线唯一标识,删除时使用
'styleId': 'style_blue',//绑定样式名
'paths': [new TMap.LatLng(40.038540, 116.272389), new TMap.LatLng(40.038844, 116.275210), new TMap.LatLng(40.041407, 116.274738)]
},
{//第2条线
'id': 'pl_2',
'styleId': 'style_red',
'paths': [new TMap.LatLng(40.039492,116.271893), new TMap.LatLng(40.041562,116.271421), new TMap.LatLng(40.041957,116.274211)]
}
]
});
var map = new TMap.Map(document.getElementById("container"), {
center: new TMap.LatLng(39.916527, 116.397128),
zoom: 11,
mapStyleId: 'style2'
});
var map = new TMap.Map(document.getElementById("container"), {
center: new TMap.LatLng(39.916527, 116.397128),
zoom: 11,
mapStyleId: 'style3'
});
一共八种免费样式map.setMapStyleId(styleId);来更换地图样式
styleId的值有八种
分别是
style0 经典:经典配色,要素鲜明,用户认知明确,适合大部分地图场景
style1 墨渊:深色主题风格,黑夜环境体验舒适,叠加亮色要素明显突出
style2 白浅:浅色系风格,简洁清新,核心要素突出,适合小清新UI风格
style3 玉露:绿色系配色,页面灵动活泼,就像一个二次元的地图世界
style4 烟翠:深沉的灰调,柔和的色彩搭配,更能体现建筑物的立体感
style5 澹月:静谧蓝做底,如恬静的月夜。适合可视化展示应用
style6 微信深色:最新深色模式下的地图样式,微信深色模式发送位置同款地图,黑夜环境下的更优体验
style7 黑色极简:以黑色简约化为特点,更加突出上层场景覆盖物的可视化呈现
下边是7种地图样式的切换案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>切换地图个性化样式</title>
</head>
<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
<style type="text/css">
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
position: relative;
}
#container {
width: 100%;
height: 100%;
}
.btn {
position: absolute;
top: 30px;
z-index: 1001;
padding: 6px 8px;
}
.btn-left1 {
left: 100px;
}
.btn-left2{
left: 200px;
}
.btn-left3 {
left: 300px;
}
.btn-left4 {
left: 400px;
}
.btn-left5 {
left: 500px;
}
.btn-left6 {
left: 600px;
}
.btn-left7 {
left: 700px;
}
</style>
<body onload="initMap()">
<div id="container"></div>
<input type="button" class="btn btn-left0" onclick="changeMapStyle('style0')" value="设置为样式0">
<input type="button" class="btn btn-left1" onclick="changeMapStyle('style1')" value="设置为样式1">
<input type="button" class="btn btn-left2" onclick="changeMapStyle('style2')" value="设置为样式2">
<input type="button" class="btn btn-left3" onclick="changeMapStyle('style3')" value="设置为样式3">
<input type="button" class="btn btn-left4" onclick="changeMapStyle('style4')" value="设置为样式4">
<input type="button" class="btn btn-left5" onclick="changeMapStyle('style5')" value="设置为样式5">
<input type="button" class="btn btn-left6" onclick="changeMapStyle('style6')" value="设置为样式6">
<input type="button" class="btn btn-left7" onclick="changeMapStyle('style7')" value="设置为样式7">
<script type="text/javascript">
var map;
function initMap() {
var center = new TMap.LatLng(39.984104, 116.307503);
//初始化地图
map = new TMap.Map("container", {
zoom: 12,//设置地图缩放级别
center: center,//设置地图中心点坐标
});
}
// 动态设置个性化样式
function changeMapStyle(styleId) {
map.setMapStyleId(styleId);
}
</script>
</body>
</html>
var tencent = new TMap.LatLng(40.040452, 116.273486);
var oldSummerPalace = new TMap.LatLng(40.006540, 116.303695);
var path = [tencent, oldSummerPalace];
// 计算路径的实际距离
var distance = TMap.geometry.computeDistance(path);
var infoDom = document.getElementById('info');
infoDom.innerText = `腾讯北京总部到圆明园的直线距离为${distance.toFixed(2)}米`;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>地址至坐标转换</title>
</head>
<script charset="utf-8"
src="https://map.qq.com/api/gljs?v=1.exp&libraries=service&key=你的key值"></script>
<style type="text/css">
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#container {
width: 100%;
height: 100%;
}
#panel {
position: absolute;
background: #FFF;
width: 300px;
padding: 20px;
z-index: 9999;
top: 30px;
left: 30px;
}
</style>
<body>
<div id="container"></div>
<div id="panel">
<p><label>地址</label><input id='address' type="text" value='北京市海淀区彩和坊路海淀西大街74号'><input id="convert" type="button"
class="btn" value="转换为坐标" onclick="convert()" /></p>
<p><label>坐标</label><input id='location' type='text' disabled value='' /></p>
</div>
</body>
<script type="text/javascript">
var map = new TMap.Map('container', {
zoom: 14,
center: new TMap.LatLng(39.986785, 116.301012),
});
var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类
var markers = new TMap.MultiMarker({
map: map,
geometries: [],
});
function convert() {
markers.setGeometries([]);
// 将给定的地址转换为坐标位置
geocoder
.getLocation({ address: document.getElementById('address').value })
.then((result) => {
markers.updateGeometries([
{
id: 'main',
position: result.result.location, // 将得到的坐标位置用点标记标注在地图上
},
]);
map.setCenter(result.result.location);
document.getElementById(
'location'
).value = result.result.location.toString();
// 显示坐标数值
});
}
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>坐标至地址转换</title>
</head>
<script charset="utf-8"
src="https://map.qq.com/api/gljs?v=1.exp&libraries=service&key=你的key值"></script>
<style type="text/css">
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#container {
width: 100%;
height: 100%;
}
#panel {
position: absolute;
background: #FFF;
width: 350px;
padding: 20px;
z-index: 9999;
top: 30px;
left: 30px;
}
</style>
<body>
<div id="container"></div>
<div id="panel">
<p><label>经纬度</label><input id='location' type="text" value='39.982915, 116.307015'><input id="convert"
type="button" class="btn" value="转换为地址" onclick="convert()" /></p>
<p><label>地址</label><input id='address' type='text' disabled value='' /></p>
</div>
</body>
<script type="text/javascript">
var map = new TMap.Map('container', {
zoom: 14,
center: new TMap.LatLng(39.986785, 116.301012),
});
var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类
var markers = new TMap.MultiMarker({
map: map,
geometries: [],
});
function convert() {
markers.setGeometries([]);
var input = document.getElementById('location').value.split(',');
var location = new TMap.LatLng(Number(input[0]), Number(input[1]));
map.setCenter(location);
markers.updateGeometries([
{
id: 'main', // 点标注数据数组
position: location,
},
]);
geocoder
.getAddress({ location: location }) // 将给定的坐标位置转换为地址
.then((result) => {
document.getElementById('address').value = result.result.address;
// 显示搜索到的地址
});
}
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>驾车路线规划</title>
</head>
<script charset="utf-8"
src="https://map.qq.com/api/gljs?v=1.exp&key=你的key值&libraries=service"></script>
<style>
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#mapContainer {
width: 100%;
height: 100%;
}
#panel {
position: absolute;
background: #FFF;
width:350px;
padding: 20px;
z-index: 9999;
top: 30px;
left: 30px;
}
</style>
<script>
var map;
function initMap() {
map = new TMap.Map('mapContainer', {
center: new TMap.LatLng(39.990619, 116.321277),
zoom: 14,
});
var startPosition = new TMap.LatLng(39.984039, 116.307630307503); // 路线规划起点
var endPosition = new TMap.LatLng(39.977263, 116.337063); // 路线规划终点
var marker = new TMap.MultiMarker({
// 创造MultiMarker显示起终点标记
id: 'marker-layer',
map: map,
styles: {
start: new TMap.MarkerStyle({
width: 25,
height: 35,
anchor: { x: 16, y: 32 },
src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png',
}),
end: new TMap.MarkerStyle({
width: 25,
height: 35,
anchor: { x: 16, y: 32 },
src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png',
}),
},
geometries: [
{
id: 'start',
styleId: 'start',
position: startPosition,
},
{
id: 'end',
styleId: 'end',
position: endPosition,
},
],
});
var driving = new TMap.service.Driving({
// 新建一个驾车路线规划类
mp: false, // 是否返回多方案
policy: 'PICKUP,NAV_POINT_FIRST', // 规划策略
});
driving.search({ from: startPosition, to: endPosition }).then((result) => {
// 搜索路径
result.result.routes[0].steps.forEach((step, index) => {
document.getElementById('instruction').innerHTML += `${index + 1}. ${
step.instruction
}`;
// 展示路线引导
});
displayPolyline(result.result.routes[0].polyline); // 绘制路径折线
});
}
function displayPolyline(pl) {
// 创建 MultiPolyline显示路径折线
var polylineLayer = new TMap.MultiPolyline({
id: 'polyline-layer',
map: map,
styles: {
style_blue: new TMap.PolylineStyle({
color: '#3777FF',
width: 8,
borderWidth: 5,
borderColor: '#FFF',
lineCap: 'round',
}),
},
geometries: [
{
id: 'pl_1',
styleId: 'style_blue',
paths: pl,
},
],
});
}
</script>
<body onload="initMap()">
<div id="mapContainer"></div>
<div id="panel"><h4>驾车路线规划</h4><div id="instruction"></div></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>下属行政区查询</title>
</head>
<script charset="utf-8"
src="https://map.qq.com/api/gljs?v=1.exp&libraries=service&key=你的key值"></script>
<style type="text/css">
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#container {
width: 100%;
height: 100%;
}
#panel {
position: absolute;
background: #FFF;
width: 350px;
padding: 20px;
z-index: 9999;
top: 30px;
left: 30px;
}
.options {
position: relative;
display: flex;
align-items: center;
width: 100%;
height: 2rem;
}
.title {
width: 3rem;
text-align: justify;
display: inline-block;
text-align-last: justify;
}
</style>
<body>
<div id="container"></div>
<div id="panel">
<h4>下属行政区查询</h4>
<div class="input-item">
<div class="title">省市区</div>
<select id='province' style="width:200px" onchange='search(this)'></select>
</div>
<div class="input-item">
<div class="title">地级市</div>
<select id='city' style="width:200px" onchange='search(this)'></select>
</div>
<div class="input-item">
<div class="title">区县</div>
<select id='district' style="width:200px" onchange='search(this)'></select>
</div>
<div class="input-item">
<div class="title">街道</div>
<select id='street' style="width:200px" onchange='search(this)'></select>
</div>
</div>
</body>
</html>
<script type="text/javascript">
var map = new TMap.Map('container', {
zoom: 8,
center: new TMap.LatLng(40, 116),
});
var provinceSelect = document.getElementById('province');
var citySelect = document.getElementById('city');
var districtSelect = document.getElementById('district');
var areaSelect = document.getElementById('street');
var provinceList = [];
var cityList = [];
var districtList = [];
var areaList = [];
var district = new TMap.service.District({
// 新建一个行政区划类
polygon: 2, // 返回行政区划边界的类型
});
var polygons = new TMap.MultiPolygon({
map: map,
geometries: [],
});
district.getChildren().then((result) => {
// 获取省市区列表及其边界信息
provinceList = result.result[0];
provinceSelect.add(new Option('---请选择---', null));
provinceList.forEach((province, index) => {
provinceSelect.add(new Option(province.fullname, index));
});
citySelect.innerHTML = '';
districtSelect.innerHTML = '';
areaSelect.innerHTML = '';
});
function search(selector) {
if (selector.id === 'province' && selector.value) {
citySelect.innerHTML = '';
districtSelect.innerHTML = '';
areaSelect.innerHTML = '';
citySelect.add(new Option('---请选择---', null));
district
.getChildren({ id: provinceList[selector.value].id })
.then((result) => {
// 根据选择的省市区获取其下级行政区划及其边界
cityList = result.result[0];
cityList.forEach((city, index) => {
citySelect.add(new Option(city.fullname, index));
});
});
drawPolygon(
provinceList[selector.value].id,
provinceList[selector.value].polygon
); // 根据所选区域绘制边界
} else if (selector.id === 'city' && selector.value) {
districtSelect.innerHTML = '';
areaSelect.innerHTML = '';
districtSelect.add(new Option('---请选择---', null));
district.getChildren({ id: cityList[selector.value].id }).then((result) => {
// 根据选择的地级市或直辖市区获取其下级行政区划及其边界
if (result.result[0].length > 0 && result.result[0][0].id.length > 6) {
// 直辖市的区的下级即为街道级,故略过一级
districtList = [];
districtSelect.innerHTML = '';
districtSelect.add(new Option('---------', null));
areaList = result.result[0];
areaSelect.add(new Option('---请选择---', null));
areaList.forEach((district, index) => {
areaSelect.add(new Option(district.fullname, index));
}); // 根据所选区域绘制边界
} else {
// 非直辖市的地级市之下有区县级
districtList = result.result[0];
districtList.forEach((district, index) => {
districtSelect.add(new Option(district.fullname, index));
});
}
});
drawPolygon(cityList[selector.value].id, cityList[selector.value].polygon);
// 根据所选区域绘制边界
} else if (selector.id === 'district' && selector.value) {
areaSelect.innerHTML = '';
district
.getChildren({ id: districtList[selector.value].id })
.then((result) => {
// 根据选择的区县获取其下级行政区划及位置
areaList = result.result[0];
areaList.forEach((area, index) => {
areaSelect.add(new Option(area.fullname, index));
});
});
areaSelect.add(new Option('---请选择---', null));
drawPolygon(
districtList[selector.value].id,
districtList[selector.value].polygon
);
} else if (selector.id === 'street' && selector.value) {
map.setCenter(areaList[selector.value].location);
// 街道级仅提供位置信息不提供边界信息,故以设置地图中心代替边界绘制
}
}
function drawPolygon(placeId, polygonArray) {
// 根据多边形顶点坐标数组绘制多边形
polygons.remove(polygons.getGeometries().map((item) => item.id));
var bounds = [];
var newGeometries = polygonArray.map((polygon, index) => {
bounds.push(fitBounds(polygon));
return {
id: `${placeId}_${index}`,
paths: polygon,
};
});
bounds = bounds.reduce((a, b) => {
return fitBounds([
a.getNorthEast(),
a.getSouthWest(),
b.getNorthEast(),
b.getSouthWest(),
]);
});
polygons.updateGeometries(newGeometries);
map.fitBounds(bounds);
}
function fitBounds(latLngList) {
// 由多边形顶点坐标数组计算能完整呈现该多边形的最小矩形范围
if (latLngList.length === 0) {
return null;
}
var boundsN = latLngList[0].getLat();
var boundsS = boundsN;
var boundsW = latLngList[0].getLng();
var boundsE = boundsW;
latLngList.forEach((point) => {
point.getLat() > boundsN && (boundsN = point.getLat());
point.getLat() < boundsS && (boundsS = point.getLat());
point.getLng() > boundsE && (boundsE = point.getLng());
point.getLng() < boundsW && (boundsW = point.getLng());
});
return new TMap.LatLngBounds(
new TMap.LatLng(boundsS, boundsW),
new TMap.LatLng(boundsN, boundsE)
);
}
</script>
腾讯地图数据可视化官网