I'm trying to draw choropleth map of Seoul but it just gives me only a black rectangle.
I thought there might be a problem with projection.scale but I couldn't figure it out.
I used scale.fitSize() function to handle it. but my d3 is older version that not available of fitSize().
my code is here:
var width = 600, height = 700;
var svg = d3.select('#chart').append('svg')
.attr('width',width)
.attr('height',height);
var projection = d3.geo.mercator()
.center([128,36])
.scale(5000)
.translate([width/2, height/2]);
var path = d3.geo.path()
.projection(projection);
d3.json('Seoulmap.json',function(error,data) {
var features = topojson.feature(data, data.objects['Seoulmap']).features;
svg.selectAll('path')
.data(features)
.enter().append('path')
.attr('class','name')
.attr('d',path)
.attr('id',function(d) { return d.properties.ADM_DR_NM; });
});
How my code is rendering black rectangle:
Related
Have a topoJSON file that I am importing - seems like this should be easy to flip, but I have no idea. Should I be transforming the object after it's created or adjusting the JSON? I tried using some projections, which flipped the object, but distorted it all over the place.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.counties {
fill: blue;
}
.states {
fill: none;
stroke: #fff;
stroke-linejoin: round;
}
</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var path = d3.geoPath()
//first make projection
//var projection = d3.geoMercator();
//var path = d3.geoPath()
// .projection(projection);
d3.json("data.topojson", function(error, us) {
if (error) throw error;
var counties = topojson.feature(us, us.objects.counties),
counties = counties.features.filter(function(d) { return d.properties.AWATER === 0; });
svg.append("g")
.attr("class", "counties")
.selectAll("path")
.data(counties)
.enter().append("path")
.attr("d", path)
.style("fill", 'blue')
.append('g')
attr('transform', 'rotate(180 0 0)');
});
</script>
You aren't using a projection - so the coordinates in the file are translated to pixels with no transformation. If your data has typical geographic coordinates, or lat longs that are both positive, high values are at the north end (the top in most maps), and low values are at the south end (the bottom in most maps).
In svg coordinates, low values are located at the top and increase as one moves towards the bottom - the opposite of most geographic coordinate conventions. You could use a geoIdentity as your projection to flip the json's y coordinates:
var projection = d3.geoIdentity()
.reflectY(true)
.fitSize([width,height],geojson)
Where geojson is your feature collection: topojson.feature(us, us.objects.counties)
And then use it with your path:
var path = d3.geoPath().projection(projection);
I am drawing a map of the United States,Costa Rica and Canada. And I would like the maps to adapt to the size of the div#statesvg
<div id="statesvg" style="width:100%; height:100%"></div>
the size of div#statesvg is dynamic.
I only want by default that the maps fits exactly to the div that contains it.
I'm trying to center each map, but it's not centered. I would like to know if there is any mathematical formula or something to scale the map until it fully occupies the svg container.
if(json=="usa.json"){
// D3 Projection
var projection = d3.geo.albersUsa()
.translate([width/2, height/2])
.scale((height*1.25));
}
if(json=="canada.json"){
//canada lat long 54.6965251,-113.7266353
var projection = d3.geo.mercator()
.center([-113.7266353,54.6965251 ])
.translate([width/2, height/2])
.scale((height*1.25));
}
if(json=="costarica.json"){
//costa rica lat long
var projection = d3.geo.mercator()
.center([-87.0531006,8.351569 ])
.translate([width/2, height/2])
.scale((height*1.25));
}
// Define path generator
var path = d3.geo.path() // path generator that will convert GeoJSON to SVG paths
.projection(projection); // tell path generator to use albersUsa projection
this is my actual problem for each map
thanks!
this is my code:
http://plnkr.co/edit/lJgx0fbLcEh7e4W3j6XD?p=preview
There is this nice gist from nrabinowitz, which provides a function which scales and translate a projection to fit a given box.
It goes through each of the geodata points (data parameter), projects it (projection parameter), and incrementally update the necessary scale and translation to fit all points in the container (box parameter) while maximizing the scale:
function fitProjection(projection, data, box, center) {
...
return projection.scale(scale).translate([transX, transY])
}
I've adapted part of your code (the Canada map) to use it:
d3.json("canada.json", function(data) {
var projection =
fitProjection(d3.geo.mercator(), data, [[0, 0], [width, height]], true)
var path = d3.geo.path().projection(projection);
d3.select("#statesvg svg").remove();
var svg = d3.select("#statesvg").append("svg")
.attr("width", width+"px")
.attr("height", height+"px");
svg.selectAll("path")
.data(data.features)
.enter()
.append("path")
.attr("d", path)
.style("stroke", "#fff")
.style("stroke-width", "1")
.style("fill", function(d) { return "rgb(213,222,217)"; });
});
As commented by the author, it seems to only work for Mercator projections.
Some background:
I have plotted a map and about 35k circles on it with zoom and tooltips working fine on SVG. However, due to the amount of circles that need to be drawn (and may be not the best written code; i'm a beginner) I see performance issues while getting the page to run.
And so, I wanted to try out the same page on a canvas to improve performance.
Problem:
I got the map itself working on canvas but I have been trying to add the zoom feature but in vain. Any help in getting this fixed will be greatly appreciated.
Sample with SVG - https://bl.ocks.org/sharad-vm/af74ae5932de1bcf5a39b0f3f849d847
The code I have for Canvas is as below:
//Width and height
var w = 700;
var h = 600;
//Create Canvas element
var canvas = d3.select('#map')
.append('canvas')
.attr('width', w)
.attr('height', h);
var context = canvas.node().getContext('2d');
//Define map projection
var projection = d3.geo.mercator()
.translate([w/2, h/1.72])
.scale([100]);
//Define path generator
var path = d3.geo.path()
.projection(projection)
.context(context);
var init = 0;
canvas.call(zoom);
var zoom = d3.behavior.zoom()
.translate([0, 0])
.scale(1)
.scaleExtent([1, 30])
.on("zoom", zoomed);
//function to zoom
function zoomed() {
context.save();
context.clearRect(0, 0, w, h);
context.translate(d3.event.transform.x, d3.event.transform.y);
context.scale(d3.event.transform.k, d3.event.transform.k);
draw();
context.restore();
};
draw();
//Load in GeoJSON data
function draw() {
...
}
When using projections the secret to get the zoom working is to transform the projection itself. For your example you can just adjust your projection before redrawing with something like:
projection.translate([w/2 + d3.event.transform.x, h/1.72 + d3.event.transform.y])
.scale([100*d3.event.transform.k]);
Another option is to scale the canvas itself, like in this example I made
I'm using Leaflet to create a map with an added D3 layer on top. I want to automatically scale and zoom to the overlay layer, similar to the way you can automatically fit geo objects within their container in pure D3 (see example).
In making Leaflet and D3 play nicely I have to use a custom geo transformation per this example:
function projectPoint(x, y) {
var point = map.latLngToLayerPoint(new L.LatLng(y, x));
this.stream.point(point.x, point.y);
}
var transform = d3.geo.transform({point: projectPoint}),
path = d3.geo.path().projection(transform);
This makes projecting D3 onto a Leaflet map effortless, but I'm left without any clue as to how to determine latitude/longitude for my layer map. I need these coordinates in order to set the center, then I'd also need to set the zoom level.
How can I set automatically setView and setZoom in Leaflet to fit a D3 overlay layer?
Here is my implementation:
var map = new L.Map("map", {
// Initialize map with arbitrary center/zoom
center: [37.8, -96.9],
zoom: 4
})
var layer = map
.addLayer(new L.TileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"));
var figure = d3.select('figure');
var width = figure.node().clientWidth;
var height = figure.node().clientHeight;
var svg = d3.select(map.getPanes().overlayPane)
.append("svg")
.style('width', width)
.style('height', height);
var g = svg.append("g").attr("class", "leaflet-zoom-hide");
function projectPoint(x, y) {
var point = map.latLngToLayerPoint(new L.LatLng(y, x));
this.stream.point(point.x, point.y);
}
var transform = d3.geo.transform({ point: projectPoint });
var path = d3.geo.path().projection(transform);
d3.json('conway-ar.json', function(error, collection) {
if (error) console.warn(error);
var city = g.append('path')
.datum(collection.city.geometry)
.attr('fill', 'none')
.attr('stroke', 'blue')
.attr('d', path);
// Update center/zoom based on location of "city"
// map.setView([someLat, someLng]);
// map.setZoom(someZoomLevel);
map.on('viewreset', update);
update();
function update() {
city.attr('d', path);
}
});
I was able to implement a solution using Leaflet.D3SvgOverlay, a library for using D3 with Leaflet that automates the geo transforms.
First I recorded the bounds of the rendered path with proj.pathFromGeojson.bounds(d). This library had a handy method that converted layer points to latitude/longitude, proj.layerPointToLatLng. I was then able to use D3's map.fitBounds to simultaneously adjust the center/zoom based on the recorded boundaries. See the following code:
var bounds = [];
var city = sel.append('path')
.datum(cityGeo)
.attr('d', function(d) {
bounds = proj.pathFromGeojson.bounds(d);
return proj.pathFromGeojson(d);
});
var b = [proj.layerPointToLatLng(bounds[0]),
proj.layerPointToLatLng(bounds[1])];
map.fitBounds(b);
The full implementation of this can be seen in my bl.ock.
A simple ball movement transition in d3.js using SVG.
jsfiddle : http://jsfiddle.net/eNe3U/1/
When I run above example, the ball looks blurred during the transition and the tranistion is not smooth.
Is there any option to get smooth transition in d3.js or am I missing something here?
Code :
var width = 720, height = 580;
var padding = 50;
var svg = d3.select("body").append("svg");
svg.attr("width",width)
.attr("height",height);
var circle = svg.append("circle")
.attr("cx","100")
.attr("cy","100")
.attr("r",10)
.attr("stroke","red")
.attr("stroke-width","1")
.attr("fill","steelblue");
circle.transition()
.duration(2000)
.attr("cx","600")
.attr("cy","700")
.attr("fill","green");