Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js Add a circle in d3.geo.path

I have created a map from a mbtile converted to a geojson, the projection is WGS84. I load it like that :

var map = svg.append("g").attr("class", "map");
var path = d3.geo.path().projection(d3.geo.albers().origin([3.4,46.8]).scale(12000).translate([590, 570]));
    d3.json('myjsonfile.json', function(json) {
        map.selectAll('path').data(json.features).enter().append('path').attr('d', path)
});

Now I would like to add a svg element (a dot, a circle, a point (i don't know)) with its (lat,lng) coordinate in my svg.

I can't figure how to do that.

like image 627
Laurent Debricon Avatar asked Apr 21 '12 18:04

Laurent Debricon


People also ask

What is the use of d3 geoPath () method?

The geographic path generator, d3. geoPath, is similar to the shape generators in d3-shape: given a GeoJSON geometry or feature object, it generates an SVG path data string or renders the path to a Canvas. Canvas is recommended for dynamic or interactive projections to improve performance.

What is path in d3 JS?

d3. path returns an object that implements the same path methods as a Canvas 2D context, but serializes them into SVG path data. With this, any program that consists of “turtle” commands can be applied to SVG as well as Canvas.


1 Answers

You need to separate out the projection so you can use it again to project the lat/lon of your point:

var map = svg.append("g").attr("class", "map");
var projection = d3.geo.albers()
    .origin([3.4,46.8])
    .scale(12000)
    .translate([590, 570]);
var path = d3.geo.path().projection(projection);
d3.json('myjsonfile.json', function(json) {
    map.selectAll('path')
        .data(json.features)
      .enter().append('path').attr('d', path);
    // now use the projection to project your coords
    var coordinates = projection([mylon, mylat]);
    map.append('svg:circle')
        .attr('cx', coordinates[0])
        .attr('cy', coordinates[1])
        .attr('r', 5);
});

Another way to do this is just to translate the dot by the projected coords:

map.append('svg:circle')
    .attr("transform", function(d) { 
        return "translate(" + projection(d.coordinates) + ")"; 
    })
    .attr('r', 5);
like image 183
nrabinowitz Avatar answered Oct 18 '22 21:10

nrabinowitz