OpenLayers 地图未渲染

OpenLayers map not rendering

我曾尝试使用 google api 在我的网站上制作地图,但是要使用它现在您需要支付很多费用。 不管怎样,我发现了 OpenLayers api 并且它很酷,但是当我请求地图以我当前位置为中心时,地图不再渲染了.-. 我的控制台没有出现任何错误,我什至使用了 promises,所以一旦我获得坐标,地图就会开始渲染。

这是我的 index.js 代码

import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

var lng;
var lat;

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function (position) {
    lat = Promise.resolve(position.coords.latitude);
    lng = Promise.resolve(position.coords.longitude);
    Promise.all([lat, lng]).then((res) => {
      console.log(res);
      const map = new Map({
        target: 'map',
        layers: [
          new TileLayer({
            source: new OSM()
          })
        ],
        view: new View({
          center: [lat, lng],
          zoom: 0
        })
      });
    })
  })
}

这是我的 html 代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Using Parcel with OpenLayers</title>
    <style>
      #map {
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script src="./index.js"></script>
  </body>
</html>

到 运行 所有这些我都在使用节点,如果我从条件中获取 const 映射,该映射将显示,但是这不是我想看到的中心 :D

OpenLayers 地图的默认投影是 EPSG:3857。地理定位 API 接收到的坐标在投影 EPSG:4326.

您需要将接收到的坐标转换为 EPSG:3857(例如使用 fromLonLat)或将地图的投影设置为 EPSG:4326