0

I try filter layer on my Leaflet jsonp from input text html to my JS code but is not working.

On my code I tried to make filter is working only when I insert number 4 directly:

let pontoFiltrado = null;
            if (feature.properties.conta === parseInt(4)) {
              pontoFiltrado = feature.geometry
            }
            
            if (pontoFiltrado) {
              let filteredLatLng = L.latLng(pontoFiltrado.coordinates[1], 
             pontoFiltrado.coordinates[0]);
              map2.setView(filteredLatLng, 19);
              // Ajustar o zoom para o nível máximo (18)
            }

But when I try to receive the value from input hmtl is not working:

let pontoFiltrado = null;
            if (feature.properties.conta === parseInt(value)) {
              pontoFiltrado = feature.geometry
            }
            
            if (pontoFiltrado) {
              let filteredLatLng = L.latLng(pontoFiltrado.coordinates[1], pontoFiltrado.coordinates[0]);
              map2.setView(filteredLatLng, 19);
              // Ajustar o zoom para o nível máximo (18)
            }

You can see my whole code below:


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
     <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin=""/>
     <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
    </head>
    <body>
        <div class="mapa" id="mapanampula" style="height: 100vh;">
          
          </div>
          <div  style="z-index: 2000; width: 400px; height: 50px;">
            <input type="text" id="meuInput" placeholder="Digite algo...">
      <button onclick="enviarParaJS()">Enviar para o JavaScript</button>
      </div>
          
    </body>
     <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="fact.js"></script>
    
    
    <script>
      var map2 = L.map('mapanampula').setView([-18.85, 36.32], 6);
    
    var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 20,
      attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
        'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
      id: 'mapbox/streets-v11',
      tileSize: 512,
      zoomOffset: -1
    }).addTo(map2);
    
    
    $.ajax('http://65.21.64.82:8080/geoserver/ows',{
    type: 'POST',
    data: {
      service: 'WFS',
      version: '1.1.0',
      request: 'GetFeature',
      typename: 'empresa:resultado',
      //CQL_FILTER: "column='demo'",
      srsname: 'EPSG:4326',
      outputFormat: 'text/javascript',
      },
    dataType: 'jsonp',
    jsonpCallback:'callback:handleJson2',
    jsonp:'format_options'
    });
    //Geojson style file
    
    var myStyle = {
      "color": "#ff9800",
      "weight": 5,
      "opacity": 0.65
     };
     
    var value;
     function enviarParaJS() {
      var valor = document.getElementById("meuInput").value;
      
      value=valor;
    
    }
    
    
    
    
    // the ajax callback function
    
    function handleJson2(data2) {
    
    
      selectedArea2 = L.geoJson(data2, {
        style: myStyle,
        onEachFeature: function(feature, layer) {
         
          layer.bindTooltip(`Name da Comunidade: ${feature.properties.nome}`)
          layer.bindPopup(`Name da Comunidade: ${feature.properties.conta}`)
    
      
      
          let pontoFiltrado = null;
                if (feature.properties.conta === parseInt(value)) {
                  pontoFiltrado = feature.geometry
                }
                
                if (pontoFiltrado) {
                  let filteredLatLng = L.latLng(pontoFiltrado.coordinates[1], pontoFiltrado.coordinates[0]);
                  map2.setView(filteredLatLng, 19);
                  // Ajustar o zoom para o nível máximo (18)
                }
              
         
        
         
        
        } 
      }).addTo(map2);
    
      
    // map2.fitBounds(selectedArea2.getBounds());
    }
    
    
    </script>
    </html>
7
  • You don't seem to pass the value variable to that function
    – Ian Turton
    Commented May 2 at 10:04
  • can you analyze my code, the value is sent from the html input text to my js and after that I need to see the filtered point layer
    – Quetions
    Commented May 2 at 10:28
  • when the point layer is filtered, the point is centralized, and zoom make more zoom in point layer
    – Quetions
    Commented May 2 at 10:29
  • This is a javascript problem not a Leaflet issue since it works when you use a specific value. All you need to do is pass value to your function or make it a global variable.
    – Ian Turton
    Commented May 2 at 14:37
  • @IanTurton Yes, it works at the time of the map load, but not if you change value later.
    – TomazicM
    Commented May 2 at 14:40

1 Answer 1

0

When you change the filter value you have to clear current features from GeoJSON layer and reload it (add data again), so that new filter value is taken into account. You can do this in enviarParaJS() function with .clearLayers() and .addData(data) methods.

Relevant part of the code could then look something like this:

var selectedArea2;
var data;  
var value;

function enviarParaJS() {
  var valor = document.getElementById("meuInput").value;
  value = valor;
  selectedArea2.clearLayers();
  selectedArea2.addData(data);
}

function handleJson2(data2) {
  data = data2;
  selectedArea2 = L.geoJson(data2, {
    style: myStyle,
    onEachFeature: function(feature, layer) {
      layer.bindTooltip(`Name da Comunidade: ${feature.properties.nome}`)
      layer.bindPopup(`Name da Comunidade: ${feature.properties.conta}`)
      let pontoFiltrado = null;
      if (feature.properties.conta === parseInt(value)) {
        pontoFiltrado = feature.geometry
      }
      if (pontoFiltrado) {
        let filteredLatLng = L.latLng(pontoFiltrado.coordinates[1], pontoFiltrado.coordinates[0]);
        map2.setView(filteredLatLng, 19);
      }
    } 
  }).addTo(map2);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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