Search code examples
javascriptleafletgeojsonstyling

Issue with styling geojson in leaflet


I'm currently working on creating a web map and I am having issues doing any styling with a polygon geojson file. I assume the issue is in the L.geoJSON(counties, {... section because when I replace it with counties.addTo(map) it draws just fine with the default rendering. I've been trying different things for the better part of the day and still haven't it right yet. Any thoughts?

<html>
    <head>
        <title>Testing Web Mapping</title>
        <link rel="stylesheet" href="leaflet/leaflet.css" />        
    </head>
    <body>
         <script src="leaflet/leaflet.js"></script>
        <div id="map" style="width:700px; height: 850px"></div>
        <script>
            var map = L.map('map',{center:[44.4340101, -90.0139754], zoom:7});
            varusgs = L.tileLayer.wms("http://basemap.nationalmap.gov/ArcGIS/services/USGSImageryOnly/MapServer/WMSServer", {layers:'0', format: 'image/png', transparent: true, attribution: "USGS"}).addTo(map);
        </script>
        <script src="leaflet/leaflet.ajax.min.js"></script>

        <script>
            var counties = new L.geoJSON.ajax('GIS/Counties_geojson.geojson');
            
            var CountiesStyle = {
                "color": "#ffffff", 
                "fillColor": "#ffffff",
                "weight": 1,
                "opacity": 1,
                "fillOpacity": 0
            };
            
            L.geoJSON(counties, {
                style: CountiesStyle
            }).addTo(map);
            counties.on('data:loaded', function(){map.fitBounds(counties.getBounds())});
        </script>
        
    </body>

</html>


Solution

  • I managed to figure out the issue through enough trial and error. If anyone comes across this post, hopefully this will help. This is the code I used:

    var counties = L.geoJSON.ajax('GIS/Counties_geojson.geojson',
        {style: CountiesStyle}).addTo(map);
        counties.on('data:loaded', function(){
        map.fitBounds(counties.getBounds())
    });
    

    Good luck to all and happy programming.