3

I'm using GeoServer for serving map in the GeoJSON format. I din't find any working example. Here is my code snippet.

<!doctype html>
<html lang="en">

<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.0.1/css/ol.css"
    type="text/css">
  <style>
    .map {
      height: 85vh;
      width: 100%;
    }
  </style>
  <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.0.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 views = new ol.View({
      center: ol.proj.fromLonLat([84.1240, 28.3949]),
      // projection: 'EPSG:4326',
      zoom: 7,
      // rotation: -Math.PI / 8,
    })

    var base_layer = new ol.layer.Tile({
      source: new ol.source.OSM()

    })

    var vectorSource = new ol.source.Vector({
      format: new ol.format.GeoJSON(),
      url: function (extent) {
        return 'http://localhost:8080/geoserver/misproject/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=misproject%3Aprovince_boundary&maxFeatures=50&outputFormat=application%2Fjson&srsname=EPSG:4326&' +
          'bbox=' + extent.join(',') + ',EPSG:4326';
      },
      strategy: new ol.loadingstrategy.bbox()
    });
    var province_boundary = new ol.layer.Vector({
      source: vectorSource,
      style: new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: 'rgba(0, 0, 255, 1.0)',
          width: 3
        })
      })
    })

    var map = new ol.Map({
      layers: [base_layer, province_boundary],
      target: 'map',
      view: views
    })
  </script>
</body>

</html>

URL is working perfectly in the postman but not in the OpenLayers. Did I miss anything?

4

OpenLayers passes the extent in view projection units so you should use that if your server supports it (otherwise you would need to transform the extent to EPSG:4326)

  url: function (extent, resolution, projection) {
    return 'http://localhost:8080/geoserver/misproject/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=misproject%3Aprovince_boundary&maxFeatures=50&outputFormat=application%2Fjson&srsname=EPSG:4326&' +
      'bbox=' + extent.join(',') + ',' + projection.getCode();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.