2013-02-07 11 views
5

Avendo il pieghevole Choropleth tutorial devo emulare un evento click su un'area specifica della mappa. Per esempio: devo avere una funzione come clickOnMapItem(itemId) che cliccare su un area della mappa che è definita dal seguente codiceEmulazione fare clic sulla mappa opuscolo elemento

{"type":"Feature","id":"05","properties":{"name":"Arkansas","density":56.43},"geometry":{"type":"Polygon","coordinates":[...} 

dove "id": "05" è l'id ho bisogno di fare clic su

il resto del mio codice è come nell'esempio:

statali data.js:

var statesData = {"type":"FeatureCollection","features":[ 
{"type":"Feature","id":"01","properties":{"name":"Alabama","density":94.65},"geometry":{"type":"Polygon","coordinates":[[[-87.359 and so on 

html:

... intestazione ommited

<!-- language:lang-html --> 
    <body> 
     <div id="map"></div> 

     <script src="dist/leaflet.js"></script> 

     <script type="text/javascript" src="us-states.js"></script> 
     <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> 
     <script type="text/javascript"> 

      var map = L.map('map').setView([37.8, -96], 4); 

      var cloudmade = L.tileLayer('http://{s}.tile.cloudmade.com/{key}/{styleId}/256/{z}/{x}/{y}.png', { 
       attribution: 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2011 CloudMade', 
       key: 'BC9A493B41014CAABB98F0471D759707', 
       styleId: 22677 
      }).addTo(map); 


      // control that shows state info on hover 
      var info = L.control(); 

      info.onAdd = function (map) { 
       this._div = L.DomUtil.create('div', 'info'); 
       this.update(); 
       return this._div; 
      }; 

      info.update = function (props) { 
       this._div.innerHTML = '<h4>US Population Density</h4>' + (props ? 
        '<b>' + props.name + '</b><br />' + props.density + ' people/mi<sup>2</sup>' 
        : 'Hover over a state'); 
      }; 

      info.addTo(map); 


      // get color depending on population density value 
      function getColor(d) { 
       return d > 1000 ? '#800026' : 
         d > 500 ? '#BD0026' : 
         d > 200 ? '#E31A1C' : 
         d > 100 ? '#FC4E2A' : 
         d > 50 ? '#FD8D3C' : 
         d > 20 ? '#FEB24C' : 
         d > 10 ? '#FED976' : 
            '#FFEDA0'; 
      } 

      function style(feature) { 
       return { 
        weight: 2, 
        opacity: 1, 
        color: 'white', 
        dashArray: '3', 
        fillOpacity: 0.7, 
        fillColor: getColor(feature.properties.density) 
       }; 
      } 
      //ON HOVER HANDLER 
      function highlightFeature(e) { 
       var layer = e.target; 
       layer.setStyle({ 
        weight: 5, 
        color: '#666', 
        dashArray: '', 
        fillOpacity: 0.7 
       }); 

       if (!L.Browser.ie && !L.Browser.opera) { 
        layer.bringToFront(); 
       } 

       info.update(layer.feature.properties); 
      } 

      var geojson; 

      function resetHighlight(e) { 
       geojson.resetStyle(e.target); 
       info.update(); 
      } 

      function zoomToFeature(e) { 

       map.fitBounds(e.target.getBounds()); 
      } 
      //setting click handlers 
      function onEachFeature(feature, layer) { 

       layer.on({ 
        mouseover: highlightFeature, 
        mouseout: resetHighlight, 
        click: zoomToFeature 
       }); 
      } 

      geojson = L.geoJson(statesData, { 
       style: style, 
       onEachFeature: onEachFeature 
      }).addTo(map); 

      map.attributionControl.addAttribution('Population data &copy; <a href="http://census.gov/">US Census Bureau</a>'); 


      var legend = L.control({position: 'bottomright'}); 

      legend.onAdd = function (map) { 

       var div = L.DomUtil.create('div', 'info legend'), 
        grades = [0, 10, 20, 50, 100, 200, 500, 1000], 
        labels = [], 
        from, to; 

       for (var i = 0; i < grades.length; i++) { 
        from = grades[i]; 
        to = grades[i + 1]; 

        labels.push(
         '<i style="background:' + getColor(from + 1) + '"></i> ' + 
         from + (to ? '&ndash;' + to : '+')); 
       } 

       div.innerHTML = labels.join('<br>'); 
       return div; 
      }; 

      legend.addTo(map); 


     </script> 
    </body> 

Grazie in anticipo!

risposta

1

Quindi si desidera emulare un evento click? Perché non usare il Leaflet's fireEvent come map.fireEvent('click',{latlng:[x,y]})

Probabilmente è necessario inserire layerPoint e containerPoint nei parametri dell'oggetto.

Vedi http://leafletjs.com/reference.html#mouse-event

+0

Ho trovato che l'argomento dell'evento non ha la proprietà 'layer': http://stackoverflow.com/q/44053812/688080 – ziyuang

6

Per aggiungere a @snkashis: fireEvent funziona solo se si immette i tipi giusti. Ciò significherebbe fare questo:

var latlngPoint = new L.LatLng(x, y); 
    map.fireEvent('click', { 
     latlng: latlngPoint, 
     layerPoint: map.latLngToLayerPoint(latlngPoint), 
     containerPoint: map.latLngToContainerPoint(latlngPoint) 
    }); 

Si può anche fare questo per uno specifico marcatore/strato di qualunque cosa se è aggiunto alla mappa.

8

Siamo spiacenti, si tratta di un 3 anni vecchia questione, ma cercherò di rispondere qui:

In primo luogo, aggiornare il codice qui sotto:

//setting click handlers 
function onEachFeature(feature, layer) { 
    layer.on({ 
    mouseover: highlightFeature, 
    mouseout: resetHighlight, 
    click: zoomToFeature 
    }); 
    //add this line 
    layer._leaflet_id = feature.id; 
} 

La nuova linea di cui sopra sarà 'assegnare' la tua di GeoJSON 'id' come leaflet_id del tuo livello, poi fare una nuova funzione come questa:

function clickOnMapItem(itemId) { 
    var id = parseInt(itemId); 
    //get target layer by it's id 
    var layer = geojson.getLayer(id); 
    //fire event 'click' on target layer 
    layer.fireEvent('click'); 
} 

quindi, non c'è bisogno t o popolare qualsiasi coordinata !!!

Spero che aiuti!

Problemi correlati