Easy example using polylabel.js by Vladimir Agafonkin: A fast algorithm for finding the pole of inaccessibility of a polygon.
Must read this post.
xxxxxxxxxx
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no">
<style >
body {
font-size: 62.5%;
}
#map {
width: 100%;
max-width: 1600px;
}
.states {
fill: rgba(245,245,245,1);
stroke: rgba(80,80,80,1);
stroke-linejoin: round;
}
.state:hover {
fill: rgba(230,230,230,1);
}
.label {
font-size: 1rem;
fill: rgba(60,60,60,1);
stroke:none;
font-family: monospace;
}
</style>
<body>
<div id="map"></div>
<script src="d3.v4.min.js"></script>
<script src="topojson.v1.min.js"></script>
<script src="polylabel.js"></script>
<script>
var width, height, map, container = d3.select("#map");
d3.json("us.json", function(map){
renderMap();
function renderMap(){
var containerWidth = container.node().getBoundingClientRect().width;
width = Math.min(containerWidth, 1600),
height = width * 0.62,
projection = d3.geoAlbersUsa()
.scale(1100)
var path = d3.geoPath()
.projection(projection)
var svg = container.append("svg")
.attr("width", width)
.attr("height", height)
var statesG = svg.append("g")
.attr("class", "states")
var states = statesG.selectAll(".state")
.data(topojson.feature(map, map.objects.states).features)
.enter()
.append("path")
.attr("d", path)
.attr("class", function(d){
return "state "+d.properties.name
})
.attr('stroke-width', '0.5')
var labelsG = svg.append("g").attr('class', 'labels')
var labels = labelsG.selectAll(".label")
.data(topojson.feature(map, map.objects.states).features)
.enter()
.append("text")
.attr('class', 'label')
.text(function(d){
//console.log(d.properties.ab,d.properties.name);
return d.properties.ab
})
.attr('transform', function(d){
// get the larget sub-polygon's coordinates
var coord = d.geometry.coordinates;
if (d.geometry.type == 'MultiPolygon') {
var u = d3.scan(
coord.map(function(p){
return -d3.polygonArea(p[0])
})
);
coord = coord[u]
}
var n = polylabel([coord[0].map(projection)])
return "translate(" + n + ")"
})
}
})
</script>
</body>
</html>