Stophface Stophface - 6 months ago 46
JSON Question

Repositioning Points on leaflet with d3 when data is js object

Considering these two examples (original code from here: Overlaying circles on leaflet with d3 results in not positioned properly):

  • Displaying points on leaflet through d3

  • a JavaScript object that contains the points

<meta charset="utf-8">
<title>D3 Test</title>
<link rel="stylesheet" href="">
<script type="text/javascript" src=""> </script>
<script src=""></script>


  • Displaying points on leaflet through d3

  • a .json file is loaded from harddrive

Why are the points in the second example repositionied when zoomed and in the first example not?!
Any explanation or pointing in the right direction is highly appreciated!


It looks like you just need to recalculate the bounds on each update.

function update() {
    circles.attr("cx", function(d) {
      return map.latLngToLayerPoint(d.LatLng).x;
    circles.attr("cy", function(d) {
      return map.latLngToLayerPoint(d.LatLng).y;

    // recalculate bounds
    var bounds = path.bounds(myPoints),
        topLeft = bounds[0],
        bottomRight = bounds[1];

    svg.attr("width", bottomRight[0] - topLeft[0])
      .attr("height", bottomRight[1] - topLeft[1])
      .style("left", topLeft[0] + "px")
      .style("top", topLeft[1] + "px");

    svgCircles.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");

The second larger example works because the points span the whole world. The bounds are the whole map and never change.

Updated plunker example.