i'm trying to load a geojson file on a leaflet map. here is the code :

body :

<!DOCTYPE html>
    <link href="leaflet.css" type="text/css" rel="stylesheet">
    <link href="index.css" type="text/css" rel="stylesheet">


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

    <script src="jquery-3.2.1.min.js"></script>
    <script src="leaflet.js"></script>
    <script src="index.js"></script>
    <script src="loc_infra.js"></script>


javascript :

var map = L.map('map',{
zoom: 3,
minZoom: 2,
maxZoom: 18,

L.tileLayer('http://{s}.tiles.mapbox.com/v3/ianmule.bg2v5cdi/{z}/{x}/{y}.png',{attribution: "Mapbox"}).addTo(map);

function basement (feature,layer){

    var c2 = L.geoJson(loc_infra, {
                weight: 4, 
                color: "red", 
                opacity: 1,
                fillColor: "red", 
                fillOpacity: 0.5
            onEachFeature: basement


and a little CSS :

html, body, #map {
height: 100%;
font-family:  : sans-serif;

and the geojson i'm trying to launch :

var loc_infra = 
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [........

but my layer is not visible on the map, and i can't understand why !


1 Answer 1


I suspect that the JavaScript code that you provide is within the index.js file?

In that case, you just have to re-order your <script> tags to make sure your loc_infra variable is defined and assigned before you try to use it:

<script src="loc_infra.js"></script> <!-- define and assign first -->
<script src="index.js"></script> <!-- now you can use it -->

Demo: http://jsfiddle.net/3v7hd2vx/263/

When programming and debugging for the Web, make sure to use the browser console / DevTools (this describes for Chrome, but all browsers have something similar). In your case, it should report the error that loc_infra variable is undefined.

Later on, you can clean your architecture by actually loading a GeoJSON file (i.e. JSON format) instead of a JS file, typically using jQuery's getJSON or through the leaflet-ajax plugin.

  • THXXXX you're a genuis <3 this is it ! i didn't know that script calling order was so important ! and you guess it right, i'm a begginer who always forget about web console :) and by your last sentence, you mean that by calling the geojson directly in the js script with "getJSON", the script calling line in the html isn't needed anymore ?
    – NanBlanc
    Apr 27, 2017 at 9:04
  • Yes, and you also do not need to wrap your GeoJSON data with var loc_infra = … ;, so that it becomes really (Geo)JSON compliant.
    – ghybs
    Apr 27, 2017 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.