Leaflet – How to Load Polygon JSON into Leaflet for Interactive Geospatial Mapping

geojsonjavascriptleafletpolygon

I want my JSON data with URL can load on the map, and it is a polygon data.
I don't know what the problem with my code.

This is my code:

<html lang="en-US" xmlns="http://www.w3.org/1999/xhtml">

<head profile="http://gmpg.org/xfn/11">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
      integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
      crossorigin="" />
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
        integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
        crossorigin=""></script>

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

<script>

    var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
        osmAttrib = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        osm = L.tileLayer(osmUrl, { maxZoom: 20, attribution: osmAttrib });
    var map = L.map('map').setView([24.151687694799833, 120.64116954803465], 15).addLayer(osm);
    L.control.scale().addTo(map);

    var states = $.getJSON("https://www.geologycloud.tw/api/v1/zh-tw/Stratum?t=.json"
        , function (data) {
            var markerGroup = L.featureGroup();
            data.value.forEach(function (itemData, itemInd) {
                for (var j = 0; j < states.features.length; j++) {
                    for (var i = 0; i < states.features[j].geometry.coordinates[0].length; i++) {
                        var po = [states.features[j].geometry.coordinates[0][i][1], states.features[j].geometry.coordinates[0][i][0]];
                        var polygon = L.polygon([po]).addTo(map);
                    }

                });
            markerGroup.addTo(map);
            map.fitBounds(markerGroup.getBounds());
        });
</script>

Best Answer

First, I had a CORS error getting the GeoJSON from the link to my map. So I hit the link and copy/pasted the date into a file called poly1.json and put this in the same folder as my page. It works. But the data source is now static not dynamic.

Your making it look difficult, try this code:

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
  integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
  crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
  integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
  crossorigin=""></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>  
      #map {
        width: 800px;
        height: 600px;
        border: 1px solid black;
        z-index: 0;
      }
</style>
</head>

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

<script>
var url ="poly1.json";   //'https://www.geologycloud.tw/api/v1/zh-tw/Stratum?t=.json';

    var map = L.map('map').setView([24.42401, 118.33202], 12); 

    var osm=new L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{ 
                attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);

// Set style function that sets fill color property
function style(feature) {
    return {
        fillColor: 'green', 
        fillOpacity: 0.5,  
        weight: 2,
        opacity: 1,
        color: '#ffffff',
        dashArray: '3'
    };
}
    var highlight = {
        'fillColor': 'yellow',
        'weight': 2,
        'opacity': 1
    };

        function forEachFeature(feature, layer) {
               var popupContent = "<p><b>Code: </b>"+ feature.properties.Code +
                "</br>Name: "+ feature.properties.Name +
                "</br>Abbrev: "+ feature.properties.Abbrev +'</p>';


            layer.bindPopup(popupContent);

            layer.on("click", function (e) { 
                stateLayer.setStyle(style); //resets layer colors
                layer.setStyle(highlight);  //highlights selected.
            }); 
        }

// Null variable that will hold layer
var stateLayer = L.geoJson(null, {onEachFeature: forEachFeature, style: style});

    $.getJSON(url, function(data) {
        stateLayer.addData(data);
    });

 stateLayer.addTo(map);

// for Layer Control    
var baseMaps = {
    "Open Street Map": osm      
};

var overlayMaps = {
    "GeoJSON":stateLayer
};  

//Add layer control
L.control.layers(baseMaps, overlayMaps).addTo(map);
 L.control.scale().addTo(map);
</script>
</body>
</html>