0

This is my code for loading one layer of .geojson data to Leaflet. The data is basically in the form of markers and it's demonstrating different location in Saudi Arabia. It's saved as "saudi_location.geojson". And my code succeeds in showing this layer on the map.

Say I have another .geojson file called "saudi_airports.geojson" and I want to load it to the map too... and I want the user to be able to toggle between the two layers, maybe check/uncheck a box to show/hide the airports layer or the location layer.

How can this be achieved?

<!DOCTYPE html>
<html>
<head>
    <title>Leaflet</title>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

        <style>
            #map {
                width: 800px;
                height: 600px;
            }
        </style>
</head>
<body>

    <div id="map">
    </div>

    <script>

        var url = 'saudi_location.geojson';  // my GeoJSON data source, in the same folder as my HTML file.
        //var map = L.map('map').setView([37.52715,-96.877441], 1);
//
//      var osm=new L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
//                  attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'});


    const map = L.map('map').setView([37.52715,-96.877441], 1);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: 'your.mapbox.access.token'
    }).addTo(map);
        var  geojsonMarkerOptions = {
                        'radius':6,
                        'opacity': .5,
                        'color': "red",
                        'fillColor':  "blue",
                        'fillOpacity': 0.8
                    };

        function forEachFeature(feature, layer) {

        var popupContent = "<p>This is <b>" +
                                    feature.properties.NAME + "it's of the type " +
                                    feature.properties.PLACE + "</br>" +
                                    '<a href="'+ feature.properties.Website +'" target="_blank">Website</a></p>' ;

                            if (feature.properties && feature.properties.popupContent) {
                                popupContent += feature.properties.popupContent;
                            }
                                layer.bindPopup(popupContent);
                    };


                    //var bbTeam = L.geoJSON(null, {onEachFeature: forEachFeature, style: style});
            var bbTeam = L.geoJSON(null, {
                            onEachFeature: forEachFeature,
                            pointToLayer: function (feature, latlng) {
                                return L.circleMarker(latlng, geojsonMarkerOptions);
                            }
                      });

                    // Get GeoJSON data and create features.
            $.getJSON(url, function(data) {
            bbTeam.addData(data);
            });

            bbTeam.addTo(map);

        </script>
    </body>
</html>
1

Here is a simple demo, data from 2 different GeoJSON files. http://www.gistechsolutions.com/leaflet/DEMO/sports/index2.html

It's just like your example, but it has 2 layers. Basically you have 2 urls, one for each source.

and a simple layer control to turn them on or off. https://leafletjs.com/reference-1.5.0.html#control-layers

| improve this answer | |
0

You can also add the separate geoJSON layers in at least two other ways:

1 - your geoJSON file is located in the main script as per below:

  var sitec = {
    "type": "FeatureCollection",
        features: [
            {
             type: "Feature",
             "properties": {
                 "Title": "Sitec IS",
                 "Head": "7400 Beach Drive",
                 "Description": "Gavin Sinclair"    
        },
            "geometry": {
            "type": "Point",
            "coordinates": [
            0.16964435577392578,
            52.29220753602784
                ]
                  }
                    },
  {
  "type": "Feature",
  "properties": {
"Title": "JHG",
    "Head": "Shortstanton sidings",
"Description": "Conor Murphy",
"Value":1,
"URL": "<a href='https://www.johnhenrygroup.co.uk/' target='blank'>JHG</a>",
"Pict": "image.png"
  },
  "geometry": {
    "type": "Point",
    "coordinates": [
      0.05458831787109375,
      52.29163006501503
    ]
  }
 }
              ]
        };

and 2nd layer:

  var test = [{
 "type": "Feature",
             "properties": {
             "Title": "Waterbeach Church",
                 "Head": "Chapel Street",
                 "Description": "Parish community"
        },
            "geometry": {
            "type": "Point",
            "coordinates": [
            0.192763,
            52.263692
                ]
                  }
                    },
   {
  "type": "Feature",
             "properties": {
             "Title": "Stretham house",
                 "Head": "Flat to leave",
                 "Description": "N/A"
        },
            "geometry": {
            "type": "Point",
            "coordinates": [
            0.211212,
            52.344149
                ]
                  }
                    }];

afterwards execute them on the map

  var geojsonMarkerOptions = { //setting the marker appearance for 1st layer
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
 };


  var sitis = L.geoJSON(sitec, {
pointToLayer: function (feature, latlng) {
feature.properties.myKey = feature.properties.Title + ', ' + feature.properties.Head
    return L.circleMarker(latlng, geojsonMarkerOptions).bindTooltip(label, {permanent: true, direction: "center", className: "my-labels"}).openTooltip(); //https://gis.stackexchange.com/questions/245621/how-to-label-geojson-points-in-leaflet
},
    onEachFeature: function (feature, layer) {
        layer.bindPopup("<h1><u><font color='red'>"+feature.properties.Title+"</h1></u></font><h2>Address: "+feature.properties.Head+"</h2><p>"+feature.properties.Description+"</p><p> Website:"+feature.properties.URL+"</p><br><center><img src='images/" + feature.properties.Pict + " ' style='width:200px;height:300x;'>");       
   }
    })
    .addTo(map);

and 2nd layer:

    var geojsonMarkerOptions2 = { //setting marker appearance for 2nd layer
radius: 5,
fillColor: "#ffc34d",
color: "#1a1100",
weight: 1,
opacity: 1,
fillOpacity: 0.4
  };


  var church = L.geoJSON(test, {
pointToLayer: function (feature, latlng) {
feature.properties.myKey = feature.properties.Title + ', ' + feature.properties.Head
label = String(feature.properties.Title)
    return L.circleMarker(latlng, geojsonMarkerOptions2).bindTooltip(label, 
 {permanent: true, opacity: 0.4}).openTooltip();
},
    onEachFeature: function (feature, layer) {
        layer.bindPopup('<h1><u><font color="red">'+feature.properties.Title+'</h1></u></font><h2>Address: '+feature.properties.Head+'</h2><p>'+feature.properties.Description+'</p><a>'+feature.properties.URL+'</a>');
  }

    }).addTo(map);

Afterwards you should have them visible on your map.

2 - fetching the geojson from an external file:

    L.layerGroup([layer1name,layer2name]).addTo(map); //name of 1st layer comes from 
    //your external .js file i.e var bt = telecom, name of 2nd layer comes from your 
     // external bp file).
| improve this answer | |

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.