I want to dynamically setView of the map based on the overlay feature which I extract from L.geoJson in Leaflet. I tried using fitBounds, which doesn't seem to work. Here is the code snippet:

 var counties = $.ajax({
          dataType: "json",
          success: console.log("data successfully loaded."),
          error: function (xhr) {

        var map = L.map('map')
           .setView([52.30, 8.23], 15); //I want to set the coordinates dynamically here like setActiveArea
         // .setActiveArea('activeArea', true, true);

        // Map layer

        var Esri_WorldImagery = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
       attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'

      //Style layer for counties
      var geojsonMarkerOptions = {
            radius: 8,
            fillColor: "#ff7800",
            color: "#000",
            weight: 1,
            opacity: 1,
            fillOpacity: 0.8

    // Add requested external GeoJSON to map
     var ky = L.geoJSON(counties.responseJSON, {
                style: geojsonMarkerOptions 
      }).bindPopup(function (layer) {
                return ("Name of the field:"+(layer.feature.properties.name)+'<br/>'+"Name" +(layer.feature.properties.sid)+"sid");

  //Just a try, doesnt seem to work either
     ky.on('load', function() {
     map.fitBounds(ky.getBounds(), {maxZoom: 3});

I tried using Leaflet plugin https://github.com/Mappy/Leaflet-active-area but got a blank output. Is there any other way to dynamically use the overlay coordinates and set it as a map view?


The answer is in your code. Just try modifying the last piece of code with getbounds(). It seems that your getting a null value, hence ur getting a blank output.

Try making these changes.

  1. Comment setView function in ur code
      var map = L.map('map');
      // .setView([52.30, 8.23], 15);
  1. Remove the ky.on() code and add setView function to map with required directions. Before this check what value ur getting in getbounds in developer options, this should help you debug better.
 map.setView(counties.getBounds()['_southWest''], 15)

Make sure to give either one of the bound as shown above (NE or SW), this could resolve your issue.

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.