Pembuatan peta
sederhana menggunakan D3.js seperti diatas menggunakan source code sebagai
berikut :
<!DOCTYPE html>
<html>
<script
src="https://d3js.org/d3.v4.js"></script>
<script
src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script
src="https://d3js.org/d3-geo-projection.v2.min.js"></script>
<head>
<title></title>
<div
id="my_dataviz"></div>
<style>
.circle:hover{
stroke: black;
stroke-width: 4px;
}
</style>
<script>
// Size ?
var width = 1280
var height = 600
// The svg
var svg =
d3.select("#my_dataviz")
.append("svg")
.attr("width", width)
.attr("height", height)
.call(d3.zoom().on("zoom",
function () {
svg.attr("transform",
d3.event.transform)
}))
.append("g")
// Map and projection
var projection = d3.geoNaturalEarth()
.center([100, 35])
.scale(width / 0.5 / Math.PI)
.translate([width / 2, height / 2])
// Create data for
circles:
// Load external data and
boot
d3.json("china.json",
function(data){
// Draw the map
svg.append("g")
.selectAll("path")
.data(data.features)
.enter()
.append("path")
.attr("fill",
"#b8b8b8")
.attr("d", d3.geoPath()
.projection(projection)
)
.style("stroke",
"black")
.style("opacity", .3)
// create a tooltip
var Tooltip =
d3.select("#my_dataviz")
.append("div")
.attr("class",
"tooltip")
.style("opacity", 1)
.style("background-color",
"white")
.style("border",
"solid")
.style("position","absolute")
/* .style("width",
"100px")*/
.style("border-width",
"2px")
.style("border-radius",
"5px")
.style("padding",
"5px")
// Three function that change the tooltip
when user hover / move / leave a cell
// Add circles:
// d3.json("data.php",
function(data) {
d3.json("data.php",
function(data) {
var mouseover = function(d) {
Tooltip
.style("opacity", 1)
.transition()
Tooltip
.duration(200)
.style("left",
(d3.mouse(this)[0]-30) + "px")
.style("top",
(d3.mouse(this)[1]) + "px")
}
var mousemove = function(d) {
Tooltip
.style("opacity",
1)
.data(data)
.html("Events ID " +
d.event_id + "<br>" +
"Jenis Kelamin: " +
d.gender + "<br>" +
"Umur: " + d.age +
"<br>" +
"Long: " +
d.longitude + "<br>" +
"Lat: " + d.latitude)
.style("left",
(d3.mouse(this)[0]) + "px")
.style("top",
(d3.mouse(this)[1]) + "px")
}
var mouseleave = function(d) {
Tooltip.style("opacity", 0)
}
svg
.selectAll("myCircles")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d){
return projection([d.longitude, d.latitude])[0] })
.attr("cy", function(d){
return projection([d.longitude, d.latitude])[1] })
.attr("r", 3)
.attr("class",
"circle")
.style("fill",
"blue")
.attr("stroke",
"white")
.attr("stroke-width", 1)
.attr("fill-opacity", 1)
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseleave", mouseleave)
});
})
</script>
</head>
<body>
</body>
</html>
|
Penjelasan :
Pembuatan
variabel SVG.
Proyeksi Peta
Memuat data json
untuk pembuatan peta
Untuk membuat
tooltip dan bubble pada peta
Event handler
untuk mouse
Isi dari file data.php
0 komentar:
Posting Komentar