Search code examples
javascriptopenlayersopenstreetmap

Show only an area using openlayer and OSM


I found this Question Show only United States when using Leaflet.js and OSM which is exactly what I'm looking for but the problem is I don't use leaflet. Currently using OpenLayers at the moment, saw some example here but no luck any ideas?

    <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([125.126012,6.066714]),
      zoom: 17,
      minZoom: 17,
      maxZoom: 18
    })
  });
</script>

Solution

  • You would need to use the view extent property. Note that it restricts the location of the center of the map.

    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([125.126012,6.066714]),
        zoom: 17,
        minZoom: 17,
        maxZoom: 18,
        extent:ol.proj.transformExtent([113,4, 119, 8], 'EPSG:4326', 'EPSG:3857')
      })
    });