Skip to content

Instantly share code, notes, and snippets.

@leenoah1
Last active May 15, 2020 13:01
Show Gist options
  • Save leenoah1/535b386ec5f5abdb2142258af395c388 to your computer and use it in GitHub Desktop.
Save leenoah1/535b386ec5f5abdb2142258af395c388 to your computer and use it in GitHub Desktop.
Mexico states d3 viz
license: mit

Mexico states

d3 map visualization exampple

Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mexico</title>
<style>
.boundary {
fill: none;
stroke: #888;
stroke-linejoin: round;
}
svg {
border-style: solid;
border-width: 1px;
border-color: #ccc;
}
#tooltip{
position: absolute;
z-index: 2;
background: rgba(0,70,30,1.0);
width:130px;
height:20px;
color:white;
font-size: 14px;
padding:5px;
top:-150px;
left:-150px;
font-family: Lucida Grande", sans-serif;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="tooltip"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>
(function() {
var height = 600;
var width = 900;
var projection = d3.geo.mercator();
var map = void 0;
var mexico = void 0;
var hover = function(d) {
console.log('d', d, 'event', event);
var div = document.getElementById('tooltip');
div.style.left = event.pageX +'px';
div.style.top = event.pageY + 'px';
div.innerHTML = d.properties.NAME_1;
};
var path = d3.geo.path().projection(projection);
var svg = d3.select("#map")
.append("svg")
.attr("width", width)
.attr("height", height);
d3.json('geo-data.json', function(data) {
var states = topojson.feature(data, data.objects.MEX_adm1);
var b, s, t;
projection.scale(1).translate([0, 0]);
var b = path.bounds(states);
var s = .9 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height);
var t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];
projection.scale(s).translate(t);
map = svg.append('g').attr('class', 'boundary');
mexico = map.selectAll('path').data(states.features);
mexico.enter()
.append('path')
.attr('d', path)
.on("mouseover", hover);
mexico.attr('fill', '#eee');
mexico.exit().remove();
});
})();
</script>
</body>
@rickrebel
Copy link

rickrebel commented May 15, 2020

Hi. I use your repo for a example in Observable in https://observablehq.com/d/42f1bf198afa4afa
Thanks for the help!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment