JavaScript调用腾讯地图API

1.申请开发者账户获取到Key值

        

        为接下来的调用做准备,同时方便后期管理和设置不同的样式操作。

2.显示地图一般分为三步:

     1.在body中预先准备地图容器,并在CSS样式中定义地图(容器)显示大小

 <div id="container"></div>

      2.在script中引入API库。

       

<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>

      3.创建并显示地图的代码(本例中,通过页面onload事件触发运行init函数初始化地图显示)本次我们以洛阳市来举例。

<script type="text/javascript">
        function initMap() {
            var center = new TMap.LatLng(34.62,112.45);
            //初始化地图
            var map = new TMap.Map("container", {
                rotation: 20,//设置地图旋转角度
                pitch:30, //设置俯仰角度(0~45)
                zoom:12,//设置地图缩放级别
                center: center
            });
        }
    </script>

3.查询行政区域查询将地图定位到洛阳市。

        1.如图所示先查询到河南省洛阳市的范围

<!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=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
<style type="text/css">
    html,
    body {
        height: 100%;
        margin: 0px;
        padding: 0px;
        overflow: hidden;
    }

    #container {
        position: relative;
        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">
      <p>请在右侧示例代码第10行填入您的key,并执行查看运行结果(key可在控制台应用管理中自行创建)</p>
        <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];
  console.log(result);
  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({ '410000' })
      .then((result) => {
        // 根据选择的省市区获取其下级行政区划及其边界
        cityList = result.result[0];
        console.log(result.result[0]);
        cityList.forEach((city, index) => {
          citySelect.add(new Option(city.fullname, index));
        });
      });
    drawPolygon(
      provinceList[selector.value].id,
      provinceList[selector.value].polygon
    ); // 根据所选区域绘制边界
  } 
    drawPolygon(cityList[selector.value].id, cityList[selector.value].polygon);
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>

2.查询到河南省洛阳市的边界地图,输出两级的result,得到控制地图的两个参数。id 和polygon,如下图所示,

3.此时我们已经得到所需地点洛阳市的所有参数信息。可以修改查询代码了,将查询功能删除,只保留省市两级别的查询,然后调用画线方法。即可绘制所需区域图形。

最终代码如下:

<!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=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
<style type="text/css">
    html,
    body {
        height: 100%;
        margin: 0px;
        padding: 0px;
        overflow: hidden;
    }

    #container {
        position: relative;
        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;
    }
</style>

<body>
    <div id="container"></div>

</body>

</html>

<script type="text/javascript">
    var map = new TMap.Map('container', {
        zoom: 8,
        center: new TMap.LatLng(40, 116),
    });
    var district = new TMap.service.District({
        // 新建一个行政区划类
        polygon: 2, // 返回行政区划边界的类型
    });
    polygons = new TMap.MultiPolygon({
        map: map,
        geometries: [],
    });
    district.getChildren({ id: '410000' }).then((result) => {
        let data = result.result;
        drawPolygon(
            data[0][2].id,
            data[0][2].polygon
        );
    });


    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>

4.后续更新在地图上添加点位和信息窗口。

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用腾讯地图JavaScript API来获取当前位置的经纬度。以下是一个使用Vue.js编写的示例代码: 1. 在`index.html`中引入腾讯地图JavaScript API: ```html <script src="https://map.qq.com/api/js?v=2.exp&key=YOUR_KEY"></script> ``` 其中,`YOUR_KEY`需要替换成你自己的腾讯地图API密钥。 2. 在Vue组件中添加一个地图容器: ```html <template> <div ref="mapContainer" style="width: 100%; height: 400px;"></div> </template> ``` 3. 在Vue组件的`mounted`生命周期钩子中初始化地图,并获取当前位置的经纬度: ```js mounted() { // 初始化地图 this.initMap(); }, methods: { initMap() { // 创建地图实例 const map = new qq.maps.Map(this.$refs.mapContainer, { center: new qq.maps.LatLng(39.916527, 116.397128), // 默认北京市中心 zoom: 13, }); // 获取当前位置的经纬度 const geolocation = new qq.maps.Geolocation(); geolocation.getLocation( (position) => { const latLng = new qq.maps.LatLng( position.lat, position.lng ); // 将地图中心设置为当前位置 map.setCenter(latLng); }, () => { console.error("定位失败"); } ); }, } ``` 在上面的代码中,我们首先创建了一个地图实例,并将地图容器绑定到Vue组件的`$refs`属性中。然后,我们使用腾讯地图的Geolocation类来获取当前位置的经纬度,并将地图中心设置为当前位置。如果定位失败,则会在控制台输出错误信息。 注意:在使用腾讯地图API时,需要先在腾讯云上开通地图API服务,并申请密钥。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值