4

I'm stumped as to how to add a GeoJSON layer to an OSM map. Through Google, I've found a bunch of different answers, none of which seem to work. Following the Leaflet documentation, the simplest way to do so is with this code:

var map = L.map('map').setView([51.505, -0.09], 15);

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

L.geoJson(data, {
        style: function (feature) {
            return { color: feature.properties.color };
        },
        onEachFeature: function (feature, layer) {
            layer.bindPopup(feature.properties.description);
        }
}).addTo(map);

Questions: what exactly do I enter for the "data" variable? I keep a file in the path "~/Scripts/worldmap.geojson", but a direct URL string doesn't work. I'm using jQuery, and it's $.getJSON function does not seem to work.

yesman
  • 478
  • 2
  • 7
  • 15

2 Answers2

7

See example https://github.com/bmcbride/bootleaf

    var boroughs = L.geoJson(null, {
    style: function(feature) {
        return {
            color: "black",
            fill: false,
            opacity: 1,
            clickable: false
        };
    },
    onEachFeature: function(feature, layer) {
        boroughSearch.push({
            name: layer.feature.properties.BoroName,
            source: "Boroughs",
            id: L.stamp(layer),
            bounds: layer.getBounds()
        });
    }
});

    $.getJSON("data/boroughs.geojson", function(data) {
        boroughs.addData(data);
    });
spatialhast
  • 3,631
  • 2
  • 27
  • 52
2

The GeoJSON needs to be formatted like a javascript object variable.

So rename the file extension of the geojson file to .js (ie. worldmap.js) and open it in your text editor.

Add:

var worldMap = [ 

in front of the data already in the file, and then a

]; 

at the end (thus turning it into a regular JSON object.)

Load the file like you would load a regular javascript file in HTML:

<script src="/Scripts/worldmap.js"></script>

...and exchange 'data' in 'L.GeoJSON(data, {...' with worldMap (the variable you just created in the other file.)

Hopefully this should work. Make sure the GeoJSON file is in WGS84 though.

hexamon
  • 2,646
  • 1
  • 16
  • 26