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.

2 Answers 2

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);
    });
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.

0

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.