Search code examples
javascripthtmlnode.jsopenlayers

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. 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 .-. I get no errors in my console , and I even used promises so the map will start rendering once I have got the coordinates .

this is my index.js code

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

<!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


Solution

  • The default projection of an OpenLayers map is EPSG:3857. The coordinates received by the geolocation API are in projection EPSG:4326.

    You need to either transform the received coordinates to EPSG:3857 (e.g. with fromLonLat) or set the projection of your map to EPSG:4326.