4

I have added WMS layer from Geoserver to show up on Leaflet. However, I would like to map automatically zoom and center to the specific feature or polygon. Does any one have any idea about this. The image attached is what I would like to do. map zoom to specific polygon

Here is my code:

  <div style="width:400px; height:400px" id="map"></div>
  <script>
  var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  { attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors' }
  );
  // Mapquest layer
  var mapquest = new L.TileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
  maxZoom: 18,
  minZoom: 5,
  attribution: "©<a href='http://openstreetmap.org/' target='_blank'>OpenStreetMap</a> contributors, Tiles Courtesy of <a href='http://open.mapquest.com' target='_blank'>MapQuest</a>",
  subdomains: ['1','2','3','4']
  });
  //create map object
  var map = new L.Map('map', {
      center: [12.565679, 104.990963],
      zoom: 8,
      layers: [mapquest]
  });

  var myLayer = new L.GeoJSON().addTo(map); 

  function loadGeoJson(data) {myLayer.addData(data); }

  var rootUrl = 'http://localhost:8181/geoserver/Land_Natural_Resources/wms';
  var layer_name = 'Land_Natural_Resources:elc_government_data_complete'; 
  var map_layer = L.tileLayer.wms(rootUrl, {
  layers: layer_name,
  format: 'image/png',
  version: '1.1.0',
  transparent: true,
  attribution: "",
  tiled:true,
  featureID:'elc_government_data_complete.1'
  }).addTo(map);  

  </script> 
user3283340
  • 63
  • 1
  • 6

1 Answers1

2

If you modify your loadGeoJson function like this:

function loadGeoJson(data) {
      myLayer.addData(data); 
      map.fitBounds(myLayer.getBounds()); 

}

This line:

map.fitBounds(myLayer.getBounds()); 

will pan your map to the bounds of the GeoJSON feature using the maximum possible zoom level for that Polygon.