Loading external GeoJSON file into Leaflet map?

  • I would like to load a geoJSON (polygon) file into my leaflet map. I have seen examples where geoJSON is embedded into the javascript code but I can't find any examples showing how it is done with an external file.

    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" />
        <script src="usStates.geojson" type="text/javascript"></script>
        <style>
            html, body, #map {
                height: 100%;
            }
            body {
                padding: 0;
                margin: 0;
            }
        </style>
    </head>
    
    <body>
        <div id="map" style="height: 100%"</div>
        <script src="http://d3js.org/d3.v2.min.js?2.9.3"></script>
        <script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js"></script>
    
        <script type="text/javascript"> 
    
        var map = L.map('map').setView([38.57, -94.71], 4);
    
        L.tileLayer('http://{s}.tile.cloudmade.com/9067860284bc491e92d2342cc51d47d9/998/256/{z}/{x}/{y}.png', {attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> Imagery © <a href="http://cloudmade.com">CloudMade</a>'}).addTo(map);
    
        var featureStyle = {
            "color": "#ff7800",
            "weight": 5, 
            "opacity": 0.2
        };
    
        L.geoJson(usStates).addTo(map);
    
        </script>
    
    </body>
    

    drag and drop the geojson onto http://geojson.io/

    @Mapperz the OP was not asking about how to paste the contents of their geojson contents into the script.

  • bailey

    bailey Correct answer

    7 years ago

    after adding var usStates = to the top of my geojson file the code worked.

    http://lyzidiamond.com/posts/osgeo-august-meeting/" target="_blank">Wayback Machine copy of above mentioned article, as the original has succumbed to linkrot, and we can't edit others' comments.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM