0

I am trying to get GeoJSON data from an API URL to an overlay.

Code;

// - GET GEOJSON DATA WITH AJAX TO OVERLAY REGION - //
// Get the data
var regions = $.ajax({
    url:"https://public.opendatasoft.com/api/records/1.0/search/?dataset=sverige-lan-counties-of-sweden&q=&lang=en&rows=37&start=0&facet=id&facet=lan_namn&facet=geo_point_2d",
    dataType: "json",
    success: console.log("Data successfully loaded!"),
    error: function (xhr) {
        alert(xhr.statusText)
    }
})

$.when(regions).done(function() {
    var regions = document.getElementById('lan_namn');
    L.geoJSON(regions, {
        pointToLayer: function (latlng) {
            return L.circleMarkers(latlng, {
                radius:6,
                opacity: .8
            })            
            .bindPopup("<p><b> " + records.fields.lan-namn + "</b></p>");
        }
    })        
});
regions.addLayer(regions);
{
  "nhits": 21,
  "parameters": {},
  "records": [
{
  "datasetid": "sverige-lan-counties-of-sweden",
  "recordid": "2bf8cfbfbd622b8d44987da4a8fdc5f957d2ed01",
  "fields": {
  "geo_shape": {},
  "id": "08",
  "lan_namn": "Kalmar län",
  "geo_point_2d": [
    57.2009990015,
    16.1929043382
  ]
},
"geometry": {
  "type": "Point",
  "coordinates": [
    16.1929043382,
    57.2009990015
  ]
},
"record_timestamp": "2019-07-15T12:39:19.034000+00:00"
},
{
  "datasetid": "sverige-lan-counties-of-sweden",
  "recordid": "b55c4a362b22739db2cdc4896ce10d1be93feb7c",
  "fields": {
    "geo_shape": {
      "type": "MultiPolygon",
      "coordinates": [
      [
        [
          [
            15.401945130895863,
            62.00965766023548
          ]
      ............
7
  • is there a console error?
    – ziggy
    Commented Jan 27, 2021 at 20:49
  • Error: regions.addLayer is not a function.. Commented Jan 27, 2021 at 20:56
  • 2
    Data you are trying to load is not GeoJSON but only JSON. See answer to similar problem: Why the icon can't display with my JSON data on Leaflet
    – TomazicM
    Commented Jan 27, 2021 at 21:08
  • @TomazicM you referring to switching the coordinates to lat lng? Commented Jan 27, 2021 at 23:06
  • You are adding regions to regions (regions.addLayer(regions)) and the region in the jQuery function stays in the function. Additionally the first regions variable is not a Layer Commented Jan 28, 2021 at 10:46

2 Answers 2

2

Your data are not in the correct geojson format, so you have to parse it by your self:

var fg = L.featureGroup().addTo(map);
fetch("https://public.opendatasoft.com/api/records/1.0/search/?dataset=sverige-lan-counties-of-sweden&q=&lang=en&rows=37&start=0&facet=id&facet=lan_namn&facet=geo_point_2d%22")
      .then(response => response.json())
      .then(data =>{
        data.records.forEach((d)=>{
          var geojson = d.fields.geo_shape;
          console.log(geojson);
          var layer = L.GeoJSON.geometryToLayer(geojson);
          fg.addLayer(layer);


          var point = L.GeoJSON.coordsToLatLng(d.geometry.coordinates);
          var circle = L.circleMarker(point,{
            radius:6,
            opacity: .8
          }).bindPopup("<p><b> " + d.fields.lan_namn + "</b></p>");
          fg.addLayer(circle);
        });
        map.fitBounds(fg.getBounds())
      })
1

There are at least five reasons why your code cannot work:

  1. API you are using to get data for GeoJSON layer does return JSON data, but this data does not have GeoJSON structure (see https://geojson.org/). To get required GeoJSON data you have to add parameter format=geojson to your API.
  2. With var regions = document.getElementById('lan_namn'); you assign DOM element to regions and then use this as input to creating GeoJSON layer. That makes no sense, input has to be GeoJSON object.
  3. Your definition of pointToLayer function is wrong. It should have two paramters, first is point feature and second point coordinates.
  4. In your popup definition you are using records.fields.lan-namn, which does not exist.
  5. Statement regions.addLayer(regions); makes no sense, you cannot add something to itself.

Below is code that works:

var regions = L.geoJSON(null, {
 pointToLayer: function (pointFeature, latlng) {
      return L.circleMarker(latlng, {
          radius:6,
          opacity: .8
      })            
      .bindPopup("<p><b> " + pointFeature.properties.lan_namn + "</b></p>");
  }  
});


$.ajax({
  dataType: "json",
  url: "https://public.opendatasoft.com/api/records/1.0/search/?dataset=sverige-lan-counties-of-sweden&q=&lang=en&rows=37&start=0&facet=id&facet=lan_namn&facet=geo_point_2d&format=geojson",
  success: function(data) {
    $(data.features).each(function(key, data) {
        regions.addData(data);
    });
    regions.addTo(map);
    map.fitBounds(regions.getBounds());
  },
  error: function(err) {
    console.log('error geojson')
  }
});
1
  • Thank you for breaking it down, explaining errors clearly. I need that, am still learning. I had 1 and 5. 4 I was sure of since the json order. 2 and 3 I knew just unsure of how..and the order of it.. and yes it works! More important, now I know why. Still a little confused over the 'key' parameter. Have to go over it some more, but Thank you! Commented Jan 28, 2021 at 11:52

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.