Only return selected GeoJSON elements in Leaflet

3k views Asked by At

I have this code that get all OSM alley elements in a map and that has a button to print all elements retrieved with Overpass API.

Instead retrieving all elements, I would like to me able to :

  1. select multiple elements on my map by clicking on those I want (the selected elements would be marked with a different color then blue).
  2. return only the selected elements.

Here is the javascript code:

        // initializing map
        var map = new L.Map('map', {
            center: L.latLng(46.827, -71.227),
            zoom: 15,
            zoomControl: false,
            layers: L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')
        });
        map.addControl(L.control.zoom({position:'topleft'}));
        var geoLayer = L.geoJson().addTo(map);

                    //getting elements on map
        $.ajax({
            data: "data=[out:json];way[highway=service][service=alley](46.822161505913414,-71.23554468154907,46.83211547933473,-71.21927976608276);(._;>;);out;",
            type: 'post',
            dataType: 'json',
            url: 'http://overpass-api.de/api/interpreter',
            success: function(json) {

                //loading warning...
                $('#preloader').hide();     
                $('#preloader')
                .ajaxStart(function(){
                    $(this).show();
                }).ajaxStop(function(){
                    $(this).hide();
                }); 

                //putting elements on map
                var geojson = osmtogeojson(json);
                geoLayer = L.geoJson(geojson, {
                    onEachFeature: function (feature, layer) {
                        //bind click
                        layer.on({
                            click: null //add a property to Feature like "selected: true" if selected is false and vice versa??????
                        });
                        //change style
                        // ??? if selected is false, keep default brue for alleys, is selected true go with light green?
                    }
                }).addTo(map);
            }
        });

        // printing elements
        function getAllElements() {

            var allMarkersObjArray = [];//new Array();
            var allMarkersGeoJsonArray = [];//new Array();

            $.each(map._layers, function (ml) {
                //console.log(map._layers)
                if (map._layers[ml].feature) {

                    allMarkersObjArray.push(this)
                    allMarkersGeoJsonArray.push(JSON.stringify(this.toGeoJSON()))
                }
            })

            console.log(allMarkersObjArray);
            alert("total Markers : " + allMarkersGeoJsonArray.length + "\n\n" + allMarkersGeoJsonArray + "\n\n Also see your console for object view of this array" );
        }

        $(".get-elements").on("click", getAllElements);

And Here is the HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
        <title></title> 
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
        <link rel="stylesheet" href="//cdn.jsdelivr.net/leaflet/0.7.3/leaflet.css"/>
        <style>
            #map {
                float:left;
                width:900px;
                height:600px;   
            }
        </style>
    </head>
    <body>
        <h4>Here are the alleys. Please select the alleys you really use and click send.</h4>
        <div id="preloader">Chargement...</div>
        <div id="map"></div>
        <input class="get-elements" type="button" value="Send" />
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="//cdn.jsdelivr.net/leaflet/0.7.3/leaflet.js"></script>
        <script src="/assets/javascripts/leaflet/osmtogeojson.js"></script>
        <script>CODE HERE</script>
    </body>
</html>

Thanks for your help!

1

There are 1 answers

0
SSA On BEST ANSWER

On each feature you can set a new property selected true and color as follows:

layer.on('click', function (e) {

//Set feature selected, you can also use layer.feature.properties
e.target.feature.properties.selected = true;

//Set style, what ever style option you want

layer.setStyle({opacity:1,width:3, fillColor:"#0080FF"});

}

To select features which are having a property selected:true, (Didn't try or test it , so may be buggy)

$.each(map._layers, function (ml) {
                //console.log(map._layers)
                if (map._layers[ml].feature && map._layers[ml].feature.properties.selected === true) {

                    allMarkersObjArray.push(this)
                    allMarkersGeoJsonArray.push(JSON.stringify(this.toGeoJSON()))
                }
            })

PS> Also no need to use $.each here, just use plain for loop