JSFiddle - React, Tailwind, and code Playground
by Alagar Kamuthurai
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/topojson/1.1.0/topojson.min.js"></script>
<div id="canvas-svg"></div>
JavaScript
function grabColor(indexNum) {
var returnNum;
var colors = [
'#000000', '#006600', '#FF0000', '#006666', '#003366',
'#0000FF', '#6600CC', '#CC33FF', '#FF33CC', '#FF6600'];
if (indexNum > 10) {
returnNum = (indexNum % 10);
} else {
returnNum = indexNum;
}
return colors[returnNum];
}
var formattedGeoObjects = [
{
shape: "point1",
color: "#000000",
location: [
-24.9609375,
36.5625
]
},
{
shape: "circle2",
color: "#FF0000",
location: [
13.359375,
31.640625],
radius: 170000.7111188
}];
var width = 800;
var height =600;
//define projection of spherical coordinates to Cartesian plane
var projection = d3.geo.mercator()
.scale((width + 1) / 2 / Math.PI)
.translate([width / 2, height / 2]);
//define path that takes projected geometry from above and formats it appropriately
var path = d3.geo.path().projection(projection);
//select the canvas-svg div and apply styling attributes
var svg = d3.select("#canvas-svg").append("svg")
.attr('width', width)
.attr('height', height)
.style({
background: '#85E0FF'
});
//convert the topoJSON back to GeoJSON
d3.json("https://s3-us-west-2.amazonaws.com/vida-public/geo/world-topo-min.json",
function (error, world) {
var countries = topojson.feature(world, world.objects.countries).features;
//give each country its own path element and add styling
svg.selectAll('.countries')
.data(countries).enter().append('path')
.attr('d', path);
//add borders around all countries with mesh
svg.append('path')
.datum(topojson.mesh(world, world.objects.countries, function () {
return true;
}))
.attr('d', path)
.style({
fill: 'none',
stroke: '#777',
'stroke-width': .5
});
var projPoint1 = [];
projPoint1 = projection([formattedGeoObjects[0].location[0],
...