cantdutchthis
cantdutchthis

Reputation: 34527

d3 circles on a leaflet map

I am using the following code to generate a map with circles;

http://jsbin.com/OTaKEDor/2/edit

<script src="http://d3js.org/d3.v3.min.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.3.9/d3.min.js"></script>
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>

<script type='text/javascript' id='lt_ws' src='http://localhost:52656/socket.io/lighttable/ws.js'></script>

<div id="map" style="width: 100%; height: 100%; position: relative;" class="leaflet-container leaflet-fade-anim" tabindex="0">
</div>

<script>
    var map = L.map('map').setView([51.82, 5.861], 11); 
  L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
      maxZoom: 18,
      attribution: ''
  }).addTo(map);

  var data = [ [5.861797,51.822823],[5.861843,51.822815],[5.5102863,51.78242],[5.8564305,51.821033],[5.859349,51.822502] ];

  var plotData = data.map( function( coord ){ 
    return map.latLngToLayerPoint( [ coord[1], coord[0] ] );
  });

  var svg = d3.select( map.getPanes().overlayPane ).append("svg"), 
      g   = svg.append("g").attr("class", "leaflet-zoom-hide");

  g.selectAll("circle").data( plotData ).enter().append("circle")
    .attr("cx", function(d){ return d.x; } )
    .attr("cy", function(d){ return d.y; } )
    .attr("r", 25)
    .style("fill", "black");

</script>

I map the coordinates to leaflet such that it is placed on the right spot. The problem is that the circles are placed on the svg on the leaflet map, google devtools confirms this, but they dont get the right attributes, they remain invisible.

See screenshot;

enter image description here

Is there something that I have forgotten to do?

Upvotes: 3

Views: 2430

Answers (1)

cantdutchthis
cantdutchthis

Reputation: 34527

this worked, this is better code as well, now the data binds to the svg elements which allows for much more interactivity;

function drawCircles(){
  var data = [
    { "coords" : [ 37.8 , - 96.8 ], "time" : 1 },
    { "coords" : [ 33.6 , - 96.6 ], "time" : 5 },
    { "coords" : [ 40.5 , - 96.3 ], "time" : 4 },
    { "coords" : [ 37.4 , - 66.6 ], "time" : 3 },
    { "coords" : [ 37.8 , - 97.6 ], "time" : 2 }
  ].map( function(d){ var newPoint = map.latLngToLayerPoint( d.coords ); d.coords = { 'x' : newPoint.x, 'y' : newPoint.y }; return d; } )

  g.selectAll("circle").data( data ).enter().append("circle")
    .attr("cx", function(d){ console.log(d); return d.coords.x } )
    .attr("cy", function(d){ return d.coords.y } )
    .attr("r", 5 )
    .style("fill", "teal")
}

Upvotes: 3

Related Questions