Skip to main content
2 of 2
deleted 83 characters in body
PolyGeo
  • 65.4k
  • 29
  • 114
  • 345

Displaying geojson polygon in leaflet imported with ajax

I'm having difficulty displaying a simple polygon in leaflet. I'm unsure if my syntax is bad or if I'm importing the geojson incorrectly. I'm using the ajax plugin from calvinmetcalf and add the js script in the head

<script src="leaflet.ajax.min.js"></script>

In the body I'm adding a base layer, specifying the polygon style, and then adding the polygon as the variable 'outline'

<body>
<div id='map'></div><script>
var map = L.map('map').setView([45.4,-112.02], 7);

// add tile base layer
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=......', {
    maxZoom: 18,
    id: 'mapbox.light'
}).addTo(map)
;

// specify polygon style for plotting
function polystyle(feature) {
return {
    fillColor: 'blue',
    weight: 2,
    opacity: 1,
    color: 'black',  //Outline color
    fillOpacity: 0.7
    };
}

// import geojson using ajax
var outline = new L.GeoJSON.AJAX("poly.geojson");      

// add outline to map
L.geoJSON(outline, {
    style: polystyle
}).addTo(map);

</script>
</body>

My poly.geojson file looks like this -- I've checked it through geojson.io and it plots fine there.

{"type":"FeatureCollection",
"crs":{"type":"name",
    "properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},
"features":[{"type":"Feature","id":0,"properties":{"Id":0},
    "geometry":{"type":"Polygon",
    "coordinates":[
        [[-112.8438,45.3956],
        [-112.4306,45.3956],
        [-112.4306,45.1617],
        [-112.8438,45.1617],
        [-112.8438,45.3956]]]
      }}]
}