在index.html中引入

<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=IVJBZ-PXLCP-GURDR-VROBE-4HQAF-U4FDK"></script>

main.js  jsonp的回调函数,必须在window下,不然指向不到

// 腾讯地图--做路线规划
window.cb = function(ret) {
    var coords = ret.result.routes[0].polyline,
      pl = [];
    //坐标解压(返回的点串坐标,通过前向差分进行压缩)
    var kr = 1000000;
    for (var i = 2; i < coords.length; i++) {
      coords[i] = Number(coords[i - 2]) + Number(coords[i]) / kr;
    }
    //将解压后的坐标放入点串数组pl中
    for (var i = 0; i < coords.length; i += 2) {
      pl.push(new TMap.LatLng(coords[i], coords[i + 1]));
    }
    display_polyline(pl); //显示路线
    //标记起终点marker
    
  }

window.display_polyline = function(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,
      },
    ],
  });
}

地图

<div id="mapContainer"></div>
initMap() {
      //初始化地图
      window.map = new TMap.Map(document.getElementById("mapContainer"), {
        center: new TMap.LatLng(34.22621,108.884623), //地图显示中心点,经纬度
        zoom: 14, //缩放级别
        disableDefaultUI: true,
      });
      //WebServiceAPI请求URL(驾车路线规划默认会参考实时路况进行计算)
      var url = `https://apis.map.qq.com/ws/direction/v1/driving/?from=${this.orderLocationList[0].latitude},${this.orderLocationList[0].longitude}&to=${this.orderLocationList[1].latitude},${this.orderLocationList[1].longitude}&output=jsonp&callback=cb&key=IVJBZ-PXLCP-GURDR-VROBE-4HQAF-U4FDK`
      this.jsonp_request(url);
      var marker = new TMap.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: new TMap.LatLng(34.22621,108.884623),
        },
        {
          id: "end",
          styleId: "end",
          position: new TMap.LatLng(34.22621,108.884623),
        },
      ],
    });
    },
    //浏览器调用WebServiceAPI需要通过Jsonp的方式,此处定义了发送JOSNP请求的函数
    jsonp_request(url) {
      var script = document.createElement("script");
      script.src = url;
      document.body.appendChild(script);
    }

 

Logo

前往低代码交流专区

更多推荐