vue中使用openlayer6同时加载高德和百度(openlayers篇)

vue中使用openlayer6同时加载高德和百度

//html
<template>
  <div>
    <div id="map" ref="mymap"></div>
  </div>
</template>

openlayer使用到的依赖

import { Map, View } from "ol";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import XYZ from "ol/source/XYZ";
import TileImage from "ol/source/TileImage";
import TileGrid from "ol/tilegrid/TileGrid";

高德图层


 this.gaodeLayer = new TileLayer({
      source: new XYZ({
        url:
          "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}"
      })
    });

百度偏移图层

// 计算百度使用的分辨率
    var resolutions = [];
    var maxZoom = 18;
    for (var i = 0; i <= maxZoom; i++) {
      resolutions[i] = Math.pow(2, maxZoom - i);
    }
    var tilegrid = new TileGrid({
      origin: [0, 0], // 设置原点坐标
      resolutions: resolutions // 设置分辨率
    });

    // 创建百度地图的数据源
    var baiduSource = new TileImage({
      projection: "EPSG:3857",//这里的坐标系一定要是3857
      tileGrid: tilegrid,
      tileUrlFunction: function(tileCoord) {
        var z = tileCoord[0];
        var x = tileCoord[1];
        /*
        !!!
        这里要注意,openlayers3之前的版本我们输出这个y是正值,但是4/5/6的版本都变成负值了,所以就参照网上3的版		   本把负值改成正值,亲测可以使用。
        至于原理为什么4以上的版本改了还需要再研究一下
        */
        var y = -tileCoord[2];

        // 百度瓦片服务url将负数使用M前缀来标识
        if (x < 0) {
          x = "M" + -x;
        }
        if (y < 0) {
          y = "M" + -y;
        }

        return (
          "http://online0.map.bdimg.com/onlinelabel/?qt=tile&x=" +
          x +
          "&y=" +
          y +
          "&z=" +
          z +
          "&styles=pl&udt=20160426&scaler=1&p=0"
        );
      }
    });
    this.baiduMapLayer = new TileLayer({
      source: baiduSource,
      visible: false
    });
let map = new Map({
      target: 'map',
      layers: [this.baiduMapLayer, this.gaodeLayer],
      view: new View({
      projection: "EPSG:4326",
      center: [116.403414, 39.924091],
      zoom: 9
    })
    })

如果有错误恳请指正

你可能感兴趣的:(vue中使用openlayer6同时加载高德和百度(openlayers篇))