简体   繁体   English

OpenLayers地图未呈现

[英]OpenLayers map not rendering

I have tried using the google api to make a map on my website however to use that now u gotta pay quite a bit. 我已经尝试过使用Google api在我的网站上制作地图,但是现在要使用它,您需要付出很多。 Anyway , I found the OpenLayers api and its cool and all however when I request the map to center on my current location the map is not getting rendered anymore .-. 无论如何,我发现了OpenLayers api及其出色的特性,但是当我要求地图以我当前位置为中心时,地图将不再呈现.-。 I get no errors in my console , and I even used promises so the map will start rendering once I have got the coordinates . 我没有在控制台中出现任何错误,甚至使用了promises,因此一旦获得坐标,地图将开始渲染。

this is my index.js code 这是我的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
        })
      });
    })
  })
}

And this is my html code 这是我的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>

to run all of this I'm using node and if I get the const map out of the conditional the map will display however that would not be the center I want to see :D 运行所有这些我正在使用的节点,如果我从条件中获取了const映射,该映射将显示,但是那不是我想看到的中心:D

The default projection of an OpenLayers map is EPSG:3857 . OpenLayers映射的默认投影为EPSG:3857 The coordinates received by the geolocation API are in projection EPSG:4326 . 地理位置API收到的坐标在投影EPSG:4326

You need to either transform the received coordinates to EPSG:3857 (eg with fromLonLat ) or set the projection of your map to EPSG:4326 . 您需要将接收到的坐标转换为EPSG:3857 (例如,使用fromLonLat )或将地图的投影设置为EPSG:4326

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM