Javascript

百度地图一套JS API,非常实用

本文主要是介绍百度地图一套JS API,非常实用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

百度地图一套JS API,非常实用

 

import mapStyleJson from "./mapStyleJson";
import $ from "jquery";

class BaiduMapGl {
  constructor(el, centerPoint, zoom) {
    this.el = el;
    this.centerPoint = centerPoint;
    this.zoom = zoom;
    this.init();
    this.sq = [];
    this.sh = [];
    this.dz = [];
    this.gb = [];
    this.jk = [];
  }
  // 初始化地图
  init() {
    this.map = new BMapGL.Map(this.el, {
      minZoom: 12,
    });
    this.setCenter(this.centerPoint, 12);
    this.map.enableScrollWheelZoom(true);
    this.map.setTilt(60);
    this.map.setMapStyleV2({
      styleJson: mapStyleJson,
    });
    return this;
  }
  // 设置地图中心点
  setCenter(centerPoint, zoom) {
    this.map.centerAndZoom(
      new BMapGL.Point(centerPoint.lng, centerPoint.lat),
      zoom
    );
  }
  // 设置地图中心
  setCenterPoint(lng, lat) {
    this.centerPoint = {
      lng,
      lat,
    };
  }
  // 绘制边界
  drawPrismOverlay(data) {
    let list = data.map((item) => {
      return new BMapGL.Point(Number(item.lng), Number(item.lat));
    });
    let prism = new BMapGL.Prism(list, 200, {
      topFillColor: "#00B0F0",
      topFillOpacity: 0.3,
      sideFillColor: "#1B9995",
      sideFillOpacity: 1,
    });
    // strokeColor: '#1B9995',
    // strokeWeight: 1,
    // strokeOpacity: 0.5,
    //  fillColor:this.colorArr[idx],
    this.map.addOverlay(prism);
    return this;
  }

  // 绘制边界
  //   drawPrismOverlay(data, border, borderOpacity, color, opacity, borderStyle) {
  //     let list = data.map((item) => {
  //         return new BMapGL.Point(Number(item.lng), Number(item.lat))
  //     })
  //     let polygon = new BMapGL.Polygon(list, {
  //         strokeColor: border || "#9200ff",//边线颜色
  //         strokeOpacity: borderOpacity || 0.5,
  //         fillColor: color || "#95d3dd",//填充颜色
  //         fillOpacity: opacity || 0.5,
  //         strokeStyle: borderStyle || "dashed",
  //         strokeWeight: 2
  //     })
  //     this.map.addOverlay(polygon)
  //     return this
  // }

  // 批量绘制markers
  batchMarkers(list, type) {
    list.forEach((item) => {
      this.drawMarker(item, type);
    });
    return this;
  }
  // 单点绘制 带label
  drawMarker({ title, point, icon, size, offset, callback }, type) {
    if (type === "default") {
      // 点
      let pt = new BMapGL.Point(point.lng, point.lat);
      // icon
      let ic = new BMapGL.Icon(icon, new BMapGL.Size(size.width, size.height));
      // 创建标注
      let marker = new BMapGL.Marker(pt, {
        icon: ic,
      });
      // 标注点击事件
      marker.addEventListener("click", function() {
        callback();
      });
      this.map.addOverlay(marker);
      // label
      let label = new BMapGL.Label(title, {
        position: pt, // 指定文本标注所在的地理位置
        offset: new BMapGL.Size(offset.x, offset.y), //设置文本偏移量
      });
      // label样式
      label.setStyle({
        color: "#fff",
        fontSize: "12px",
        height: "20px",
        lineHeight: "20px",
        fontFamily: "微软雅黑",
        background: "transparent",
        border: "none",
      });
      this.map.addOverlay(label);
    } else if (type === "sq") {
      // 点
      let pt = new BMapGL.Point(point.lng, point.lat);
      // icon
      let ic = new BMapGL.Icon(icon, new BMapGL.Size(size.width, size.height));
      // label
      // 创建标注
      let marker = new BMapGL.Marker(pt, {
        icon: ic,
      });
      this.map.addOverlay(marker);

      // 标注点击事件
      marker.addEventListener("click", function() {
        callback();
      });
      marker.addEventListener("mouseover", function() {
        // 为标注设置标签
        let label = new BMapGL.Label(title, {
          position: pt, // 指定文本标注所在的地理位置
          offset: new BMapGL.Size(offset.x, offset.y), //设置文本偏移量
        });
        // label样式
        label.setStyle({
          color: "#fff",
          fontSize: "12px",
          height: "20px",
          lineHeight: "20px",
          fontFamily: "微软雅黑",
          background: "transparent",
          border: "none",
        });
        marker.setLabel(label);
      });
      marker.addEventListener("mouseout", function() {
        var label = this.getLabel();
        //设置标签内容为空
        label.setContent("");
        label.setStyle({ display: "none" });
      });
      this.sq.push(marker);
      //   console.log(this.sq);
    } else if (type === "dz") {
      // 点
      let pt = new BMapGL.Point(point.lng, point.lat);
      // icon
      let ic = new BMapGL.Icon(icon, new BMapGL.Size(size.width, size.height));
      // label
      // 创建标注
      let marker = new BMapGL.Marker(pt, {
        icon: ic,
      });
      this.map.addOverlay(marker);
      let label = new BMapGL.Label(title, {
        position: pt, // 指定文本标注所在的地理位置
        offset: new BMapGL.Size(offset.x, offset.y), //设置文本偏移量
      });

      // 标注点击事件
      marker.addEventListener("click", function() {
        callback();
      });
      marker.addEventListener("mouseover", function() {
        // 为标注设置标签
        let label = new BMapGL.Label(title, {
          position: pt, // 指定文本标注所在的地理位置
          offset: new BMapGL.Size(offset.x, offset.y), //设置文本偏移量
        });
        // label样式
        label.setStyle({
          color: "#fff",
          fontSize: "12px",
          height: "20px",
          lineHeight: "20px",
          fontFamily: "微软雅黑",
          background: "transparent",
          border: "none",
        });
        marker.setLabel(label);
      });
      marker.addEventListener("mouseout", function() {
        var label = this.getLabel();
        //设置标签内容为空
        label.setContent("");
        label.setStyle({ display: "none" });
      });
      this.dz.push(marker);
    } else if (type === "gb") {
      // 点
      let pt = new BMapGL.Point(point.lng, point.lat);
      // icon
      let ic = new BMapGL.Icon(icon, new BMapGL.Size(size.width, size.height));
      // label
      // 创建标注
      let marker = new BMapGL.Marker(pt, {
        icon: ic,
      });
      this.map.addOverlay(marker);

      // 标注点击事件
      marker.addEventListener("click", function() {
        callback();
      });
      marker.addEventListener("mouseover", function() {
        // 为标注设置标签
        let label = new BMapGL.Label(title, {
          position: pt, // 指定文本标注所在的地理位置
          offset: new BMapGL.Size(offset.x, offset.y), //设置文本偏移量
        });
        // label样式
        label.setStyle({
          color: "#fff",
          fontSize: "12px",
          height: "20px",
          lineHeight: "20px",
          fontFamily: "微软雅黑",
          background: "transparent",
          border: "none",
        });
        marker.setLabel(label);
      });
      marker.addEventListener("mouseout", function() {
        var label = this.getLabel();
        //设置标签内容为空
        label.setContent("");
        label.setStyle({ display: "none" });
      });
      this.gb.push(marker);
    } else if (type === "jk") {
      // 点
      let pt = new BMapGL.Point(point.lng, point.lat);
      // icon
      let ic = new BMapGL.Icon(icon, new BMapGL.Size(size.width, size.height));
      // label
      // 创建标注
      let marker = new BMapGL.Marker(pt, {
        icon: ic,
      });
      this.map.addOverlay(marker);

      // 标注点击事件
      marker.addEventListener("click", function() {
        callback();
      });
      marker.addEventListener("mouseover", function() {
        // 为标注设置标签
        let label = new BMapGL.Label(title, {
          position: pt, // 指定文本标注所在的地理位置
          offset: new BMapGL.Size(offset.x, offset.y), //设置文本偏移量
        });
        // label样式
        label.setStyle({
          color: "#fff",
          fontSize: "12px",
          height: "20px",
          lineHeight: "20px",
          fontFamily: "微软雅黑",
          background: "transparent",
          border: "none",
        });
        marker.setLabel(label);
      });
      marker.addEventListener("mouseout", function() {
        var label = this.getLabel();
        //设置标签内容为空
        label.setContent("");
        label.setStyle({ display: "none" });
      });
      this.jk.push(marker);
    }
  }

  // 地图旋转动画
  enableAnimation() {
    const keyFrames = [
      {
        center: new BMapGL.Point(this.centerPoint.lng, this.centerPoint.lat),
        zoom: 12,
        tilt: 60,
        heading: 0,
        percentage: 0,
      },
      {
        center: new BMapGL.Point(this.centerPoint.lng, this.centerPoint.lat),
        zoom: this.zoom,
        tilt: 50,
        heading: 360,
        percentage: 1,
      },
    ];
    const opts = {
      duration: 1000, // 设置每次迭代动画持续时间
      delay: 3000, // 设置动画延迟开始时间
      interation: 1, // 设置动画迭代次数
    };
    const animation = new BMapGL.ViewAnimation(keyFrames, opts); // 初始化动画实例
    this.map.startViewAnimation(animation);
    return this;
  }
  // 清除所有markers及labels
  clearAllMarkers() {
    // 获取所有覆盖物
    let length = this.map.getOverlays().length;
    for (let i = length; i > 0; i--) {
      let marker = this.map.getOverlays()[i - 1];
      // 去除marker及label
      if (marker.toString() == "Marker" || marker.toString() == "Label") {
        this.map.removeOverlay(marker);
      }
    }
  }
  // 清除所有覆盖物
  clearOverlays() {
    this.map.clearOverlays();
  }
  // 获取小区uid
  getLocalUid(XQ) {
    const local = new BMapGL.LocalSearch(this.map, {
      renderOptions: { map: this.map },
    });
    local.setMarkersSetCallback((pois) => {
      console.log(pois);
      pois.map((v) => {
        this.map.removeOverlay(v.marker);
      });
      const uid = pois[0].uid;
      this.drowBoundary(uid);
    });
    local.search(XQ);
  }
  //小区边界
  drowBoundary(uid) {
    $.ajax({
      async: false,
      url:
        "http://map.baidu.com/?pcevaname=pc4.1&qt=ext&ext_ver=new&l=12&uid=" +
        uid,
      dataType: "jsonp",
      jsonp: "callback",
      success: (result) => {
        console.log(result);
        const content = result.content;
        if (content.geo != null && content.geo != undefined) {
          const geo = content.geo;
          let points = this.coordinateToPoints(geo);
          //point分组,得到多边形的每一个点,画多边形
          if (points && points.indexOf(";") >= 0) {
            points = points.split(";");
          }
          var arr = [];
          for (let i = 0; i < points.length - 1; i++) {
            var temp = points[i].split(",");
            arr.push(
              new BMapGL.Point(parseFloat(temp[0]), parseFloat(temp[1]))
            );
          }
          //创建多边形
          let polygon = new BMapGL.Prism(arr, 50, {
            topFillColor: "#00B0F0",
            topFillOpacity: 0.3,
            sideFillColor: "#1B9995",
            sideFillOpacity: 0.8,
          });
          this.map.addOverlay(polygon); //增加多边形
          this.map.setViewport(polygon.getPath());
        } else {
          console.log("暂无小区边界信息");
        }
      },
    });
  }
  //百度米制坐标转换为经纬度
  coordinateToPoints(coordinate) {
    let points = "";
    if (coordinate) {
      const projection = BMAP_NORMAL_MAP.getProjection();
      if (coordinate && coordinate.indexOf("-") >= 0) {
        coordinate = coordinate.split("-");
      }
      //取点集合
      let tempco = coordinate[1];
      if (tempco && tempco.indexOf(",") >= 0) {
        tempco = tempco.replace(";", "").split(",");
      }
      //分割点,两个一组,组成百度米制坐标
      let temppoints = [];
      for (let i = 0, len = tempco.length; i < len; i++) {
        temppoints.push({
          lng: tempco[i],
          lat: tempco[i + 1],
        });
        i++;
      }
      for (let i = 0, len = temppoints.length; i < len; i++) {
        let pos = temppoints[i];
        let point = projection.pointToLngLat(
          new BMapGL.Pixel(pos.lng, pos.lat)
        );
        points += [point.lng, point.lat].toString() + ";";
      }
    }
    return points;
  }
}

export default BaiduMapGl;

 

这篇关于百度地图一套JS API,非常实用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!