Search code examples
leafletgeojson

Load GeoJson file for Leaflet choropleth


I have a GeoJson file that I am trying to load to logic.js for the Leaflet. I console.logged the response and it fetches the data, however, when I try to apply the data onto the map, it gives me the following error: Uncaught (in promise) Error: Invalid GeoJSON object. My GeoJSON data looks like this:

  "type": "WineCollection",
  "wines": [
    {
      "type": "wine",
      "properties": {
        "country": "Albania",
        "points": 88.0,
        "price": 20.0
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          19.9999619,
          41.000028
        ]
      }
    },

Here is my code:

  center: [40.7128, -74.0059],
  zoom: 2.5
});

// Adding tile layer
L.tileLayer("https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}", {
  attribution: "Map data &copy; <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>",
  maxZoom: 18,
  id: "mapbox.streets",
  accessToken: API_KEY
}).addTo(myMap);

d3.json("static/js/wine.json").then(function(data) {
  L.geoJson(data).addTo(myMap);
});

Solution

  • The data sample is not compliant with GeoJSON specification.

    You can have an object of type "FeatureCollection", having an array of "features", which are objects of type "Feature" (and having "properties" and a "geometry" like in your data sample).

    Unfortunately you cannot customise those types.

    There are several GeoJSON linting tool available that can help you quickly spot non compliant data, e.g. http://geojsonlint.com/