Fabio
Fabio

Reputation: 67

Load osm file using openlayers 3

I am using openlayers 3 (http://openlayers.org/) and i am trying to load an osm file in my map. In the old version of openlayers this task is very simple (http://wiki.openstreetmap.org/wiki/OpenLayers_osm_file_example) but now using openlayers 3 i cannot do a similar thing.

Any suggestion?

Upvotes: 4

Views: 2860

Answers (2)

alex
alex

Reputation: 955

i had the same question but the answer given above isn't accessible.

i ended in inquiring the matter alone, and posted the compatible ol 3+ solution on the osm wiki, right under the original ol 2 example.

here are the ol2 and ol3 examples

here's my full example:

<html>
    <head>
        <title>OpenLayers 3+ .osm File Example</title>
        
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/ol.css" />
<script src="https://unpkg.com/[email protected]/dist/ol-layerswitcher.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/ol-layerswitcher.css" />

        <script type="text/javascript">
            var lat=34.070;
            var lon=-118.73;
            var zoom=15;
            let osmFile = 'display-osm.osm';


function init(){                                                                             
    var map, layer, center;                                                                 
    map = new ol.Map({                                                                   
        target:'map',                                                                   
        renderer:'canvas',                                                           
        view: new ol.View({                                                         
            projection: 'EPSG:900913',                                           
        })                                                                       
    });                                                                             
    const baseOSM = new ol.layer.Tile({                                                         
        title: 'baseOSM',
        source: new ol.source.OSM()                                                 
    });                                                                             
    map.addLayer(baseOSM); // this can actually come up last                                 
    center = new ol.proj.transform(
        [lon, lat],
        'EPSG:4326', // essentially LonLat                      
        map.getView().getProjection()
    );                       
    map.getView().setCenter(center);                                                         
    map.getView().setZoom(zoom);                                                                
    const formatOSM = new ol.format.OSMXML();
    const vectorSource = new ol.source.Vector({
        format: formatOSM,
        loader: function (extent, resolution, projection, success, failure) {
            const epsg4326Extent = ol.proj.transformExtent(extent, projection, 'EPSG:4326');
            fetch(osmFile).then(reply => {
                reply.text().then(replyText => {
                    const features = formatOSM.readFeatures(replyText, {
                        featureProjection: map.getView().getProjection(),
                    });
                    vectorSource.addFeatures(features);
                    success(features);
                });
            }).catch(failure);
        },
        strategy: ol.loadingstrategy.fixed,
    });
    
    const dim_orange = ol.color.asString(
        ol.color.asArray('orange').slice(0, 3).concat(0.1));
    const localOSM = new ol.layer.Vector({
        title: 'localOSM',
        source: vectorSource,
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'orange',
                width: 1,
            }),
            fill: new ol.style.Fill({
                color: dim_orange,
            }),
            image: new ol.style.Circle({
                fill: new ol.style.Fill({
                    color: dim_orange,
                }),
                radius: 6,
                stroke: new ol.style.Stroke({
                    color: 'orange',
                    width: 1,
                }),
            }),
        }),
    });
    
    map.addLayer(localOSM);
    let layerSwitcher = new ol.control.LayerSwitcher({
        tipLabel: 'Légende' // Optional label for button
    });
    map.addControl(layerSwitcher);
}
        </script>
    </head>
    <body onload="init()">
        <div id="map"></div>
        <div id="explanation">OpenLayers displaying a .osm file directly. This <a href="display-osm.osm">display-osm.osm</a> is a very small example. Most .osm files would be too large to do this, and in general you're more likely to load in vector features in a different way</div>
    </body>
</html>

Upvotes: 0

Asher
Asher

Reputation: 2774

A Simple "OpenLayers 3" (Open Street Maps) Example

If you are trying to use OpenLayers 3 you might try using the https://openlayers.org/en/latest/doc/quickstart.html example it works locally really well and is fairly simple JavaScript.

OpenLayers (Open Street Maps) uses the following two files in the code...

<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v6.1.1/build/ol.js"></script>
<link rel="stylesheet"
href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v6.1.1/css/ol.css">

https://openlayers.org/en/latest/doc/quickstart.html

Here is the code from the above example if you need to test it out locally on your computer.

<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" type="text/css">
    <style>
      .map {
        height: 400px;
        width: 100%;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
    <title>OpenLayers example</title>
  </head>
  <body>
    <h2>My Map</h2>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([37.41, 8.82]),
          zoom: 4
        })
      });
    </script>
  </body>
</html>

Upvotes: 0

Related Questions