openlayers6 使用ol.map>ol.view center属性无效及解决方案

openlayers6 使用ol.map>ol.view center属性无效及解决方案

原因分析:

The initial center for the view. If a user projection is not set, the coordinate system for the center is specified with the projection option. Layer sources will not be fetched if this is not set, but the center can be set later with #setCenter.

以上是来自ol api官方文档的原话,大致意思为如果不设置那么图层就不会提取,也就是页面会一片空白。
在这里插入图片描述
很明显这不是center失效的原因😁。
那么再来看看这段:

The default projection is Spherical Mercator (EPSG:3857).

这里告知我们ol.view 的默认投射格式是EPSG:3857。但是日常我们使用的经纬度格式是EPSG:4326。所以你给center设置成[109,34]这种当然是没有效果的,至于为什么会使用[109,34],相信大家也是深受csdn中一些半吊子的荼毒。很多帖子是直接这样设置的。也没有设置ol.view的projection为EPSG:4326,所以问题解决了,设置projection为EPSG:4326就行了。但是得到结果如下:
在这里插入图片描述
很明显视图已经变形了,这不是我们想要的结果,经过深思熟虑还是想办法将EPSG:4326转成EPSG:3857吧,估计是ol.map的适配问题吧(有清楚的跪求告知)。
使用ol/proj中的transform进行转换,至于为什么我知道,多翻文档。最终代码如下:

<template>
  <div id="ol-container"></div>
</template>
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import {transform} from "ol/proj"
export default {
  name: "OlMap",
  mounted() {
    this.initOl();
  },
  methods: {
    initOl() {
      this.map = new Map({
        target: "ol-container",
        layers: [
          new TileLayer({
            source: new XYZ({
              url:
                "http://t3.tianditu.com/DataServer?T=img_w&tk=我的key差点暴露- - ·&x={x}&y={y}&l={z}",
            }),
          }),
        ],
        view: new View({
          center: transform([109, 34], 'EPSG:4326', 'EPSG:3857'),
            // center:[109,34],
          zoom: 2,
          maxZoom: 15,
        //   projection:'EPSG:4326'
        }),
      });
    },
  },
};
#ol-container {
  width: 100%;
  height: 100vh;
}

在这里插入图片描述

—————————————————————————————————————
好了 板板整整

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值