OpenLayers – Drawing GeoJSON with D3js on OpenLayers 4

d3geojsonopenlayers

The goal is to interact with the DOM based on users input using JavaScript. I have now considered using D3js (v5) to draw the points. Without the base vector layers (loaded as a geojson) and OpenLayers, the data gets drawn with D3js but when put together I do not see it on. Below is my code.

For JavaScript files

    var width = 800,
    height = 800;
var svg = d3.select("#map")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

var files = ['../data/mines.geojson', "../data/mines_centroid.geojson"];

var promises = [];

files.forEach(function (url) {
    promises.push(d3.json(url))
});

Promise.all(promises).then(function (val) {
    drawMap(val[0], val[1])
});

var projection = d3.geoMercator();

var geoPath = d3.geoPath()
    .projection(projection);

var radius = d3.scaleLog();

function drawMap(mines, centroid) {
    projection.center([22.9696994071445, 40.8135651828386]);
    projection.fitSize([width, height], mines);
    svg.append("g")
        .selectAll("path")
        .data(mines.features)
        .enter()
        .append("path")
        .attr("d", geoPath)
        .attr("stroke", "blue")
        .attr("fill", "white")
        .attr("class", "mines");
    addCentroid(centroid)
}

function addCentroid(centroid) {
    console.log(centroid)

    var points = svg.selectAll("circle")
        .data(centroid.features, function (d) {
            return d;
        })
        .enter().append("circle")
        .attr('r', function (d) {
            return radius(d.properties.Scale) * 1.5
        })
        .attr('cx', function (d) {
            return projection(d.geometry.coordinates)[0]
        })
        .attr('cy', function (d) {
            return projection(d.geometry.coordinates)[1]
        })
        .attr("class", "centroid")
        .attr("id", function (d) {
            return d.properties.ID
        })


}

My GeoJSON looks like this.

{
  "type": "FeatureCollection",
  "crs": {
    "type": "name",
    "properties": {
      "name": "EPSG:4326"
    }
  },
  "features": [
    {
      "type": "Feature",
      "id": 1,
      "geometry": {
        "type": "Point",
        "coordinates": [
          22.9696994071445,
          40.8135651828386
        ]
      },
      "properties": {
        "FID": 1,
        "OBJECTID": 119,
        "ID": "GR-4291",
        "Code_12": "131",
        "Remark": " ",
        "Scale": 10,
        "Area_ha": 95.6086248776,
        "Shape_Leng": 6533.9468799,
        "code00": 13,
        "Shape_Le_1": 6533.9468799,
        "Shape_Area": 956086.248776,
        "ORIG_FID": 0
      }
    }
]
}

Best Answer

Fixing some minor issues in your code makes the example work. Some of them were:

  1. Linking d3js v5 instead of v3.
  2. Making the svg position absolute on the same position as the map.

Here is the cleaned up code showing your features on the map.

enter image description here

Related Question