Example demonstrating the use of d3 v4 and mapbox-gl-js
-
-
Save kmandov/70be1f3b2648ad2be1cdf1feb5afbb4d to your computer and use it in GitHub Desktop.
MapboxGL & D3.js - polygon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> | |
<title>MapboxGL & D3.js - dpolygon</title> | |
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.12.0/mapbox-gl.css' rel='stylesheet' /> | |
<style> | |
html, body, #wrapper { | |
width: 100%; | |
height: 100%; | |
padding: 0px; | |
margin: 0px; | |
} | |
#map { | |
position:relative; | |
width: 100%; | |
height: 100%; | |
margin: auto auto; | |
} | |
svg { | |
position: absolute; | |
width: 100%; | |
height: 100%; | |
} | |
.hidden { | |
display: none; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="wrapper"> | |
<div id="map"></div> | |
</div> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.12.0/mapbox-gl.js'></script> | |
<script> | |
d3.json("ken.geojson", function(err, data) { | |
mapDraw(data); | |
}); | |
function mapDraw(geojson){ | |
//mapboxgs トークン | |
mapboxgl.accessToken = 'pk.eyJ1Ijoic2hpbWl6dSIsImEiOiI0cl85c2pNIn0.RefZMaOzNn-IistVe-Zcnw' | |
//Setup mapbox-gl map | |
var map = new mapboxgl.Map({ | |
container: 'map', // container id | |
style: 'mapbox://styles/mapbox/streets-v8', | |
center: [141.15448379999998, 39.702053 ], | |
zoom: 4, | |
}) | |
map.addControl(new mapboxgl.Navigation()); | |
var container = map.getCanvasContainer() | |
var svg = d3.select(container).append("svg") | |
var transform = d3.geoTransform({point: projectPoint}); | |
var path = d3.geoPath().projection(transform); | |
var featureElement = svg.selectAll("path") | |
.data(geojson.features) | |
.enter() | |
.append("path") | |
.attr("d", d3.geoPath().projection(transform)) | |
.attr("stroke", "red") | |
.attr("fill", "green") | |
.attr("fill-opacity", 0.4); | |
// update the path using the current transform | |
function update() { | |
featureElement.attr("d", path); | |
} | |
// | |
map.on("viewreset", update) | |
map.on("movestart", function(){ | |
svg.classed("hidden", true); | |
}); | |
map.on("rotate", function(){ | |
svg.classed("hidden", true); | |
}); | |
map.on("moveend", function(){ | |
update() | |
svg.classed("hidden", false); | |
}) | |
//初期レンダリング | |
update() | |
function projectPoint(lon, lat) { | |
var point = map.project(new mapboxgl.LngLat(lon, lat)); | |
this.stream.point(point.x, point.y); | |
} | |
} | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment