Search code examples
javascriptvectoropenlayerslocaltiles

Openlayers 4+ using local vector tiles (.pbf) without server


I'm new in online mapping, and in the past I've created raster maps succesfully with Maperitive from osm data. It works fine from localhost/ local folder structure. But my question: Is it possible to serve local vector maps from .pbf or geojson files without any server or mapbox stuff just like raster images? Is it possible to render without any server or api key required service in the browser directly in the client side? If yes, could someone provide me a working example?

Thanks.


Solution

  • Normally websites cannot access your local file system. This is to protect you and your computer from websites spying on you.

    However, there are exceptions to that rule.

    1. Websites can read files that you selected in a "upload file" input element.
    2. A page can read file system, when it is opended from the disk

    Opening an html document from the harddrive means that you simply double click it on your computer and the browser opens it. All relative links in that html document are then relative to that document.

    So if you use the GeoJSON class, you can simply give it a path to files on your computer. Here is an example that reads a local file named mygeojson.geojson from a folder mysubfolder and shows it on top of a OpenStreetMap layer:

    var map = new ol.Map({
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        }),
        new ol.layer.Image({
          source: new ol.source.ImageVector({
            source: new ol.source.Vector({
              url: 'mysubfolder/mygeojson.geojson',
              format: new ol.format.GeoJSON()
            }),
            style: new ol.style.Style({
              fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.6)'
              }),
              stroke: new ol.style.Stroke({
                color: '#319FD3',
                width: 1
              })
            })
          })
        })
      ],
      target: 'map',
      view: new ol.View({ center: [0, 0], zoom: 1 })
    });