Displaying interactive maps with OpenLayers





Introduction to OpenLayers

OpenLayers is a Javascript library that allows you to put any map on the website. OpenLayers also support XYZ map tiles that strues-maps.lt can provide. We recommend using EPSG:3857 projection for strues-maps, and minimum-maximum zoom levels together with the constrained extent to limit the number of tiles a visitor might request while browsing your map. Below you can see an example map of Baltic states and the JavaScript code used to render it. Also, strues-maps.lt indirectly uses OpenStreetMap data, which requires copyright attribution.


Example map of Baltic states


Example OpenLayers code v10.4.0

<link href="https://cdn.jsdelivr.net/npm/ol@v10.4.0/ol.css"
    type="text/css" rel="stylesheet">
<script
    src="https://cdn.jsdelivr.net/npm/ol@v10.4.0/dist/ol.js" 
    type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.15.0/proj4.js"></script>
<div id='map' style='width:100%;height:512px;border:1px;'></div>                                  

<script type="text/javascript">
    var API_KEY = 'API_KEY';
    var SIG = 'SIG';

    var centerPoint = [24.06, 56.57];
    var leftBottom = [19.7225, 52.4849];
    var rightTop = [30.9395, 60.2197];

    var source = new ol.source.XYZ({
        url: 'https://api.strues-maps.lt/v1/tms/{z}/{x}/{-y}.jpeg?api_key='+
           API_KEY+'&signature='+SIG,
        attributions: '&#169; <a href="https://www.openstreetmap.org/copyright" '+
           'target="_blank">OpenStreetMap</a> contributors.'
    });

    var WGS84 = 'EPSG:4326';
    var EPSG3857 = 'EPSG:3857';
    var projection = new ol.proj.Projection({
        code: 'EPSG:3857',
        units: 'm',
        axisOrientation: 'neu'
    });
    
    centerPoint = proj4(WGS84, EPSG3857, centerPoint);
    leftBottom = proj4(WGS84, EPSG3857, leftBottom);
    rightTop = proj4(WGS84, EPSG3857, rightTop);

    var layer = new ol.layer.Tile({source: source});
    var maxExtent = [leftBottom[0], leftBottom[1], rightTop[0], rightTop[1]];
    var maxZoom = 9;
    var minZoom = 7;

    var view = new ol.View({
        center: centerPoint,
        zoom: 7,
        projection: projection,
        maxZoom: maxZoom, // Maximum zoom level
        minZoom: minZoom, // Minimum zoom level
        extent: maxExtent // Limit map to the specified extent
    });

    var map = new ol.Map({
        layers: [layer],
        target: 'map',
        view: view
    });
 </script> 


API_KEY and SIG variables

In the example code above, two custom variables are used: API_KEY and SIG. In order to display interactive maps on your website, you must get a free API key. Depending on your map traffic some costs may incur.