Skip to content

Instantly share code, notes, and snippets.

@kmandov
Forked from shimizu/README.md
Last active February 20, 2023 08:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmandov/70be1f3b2648ad2be1cdf1feb5afbb4d to your computer and use it in GitHub Desktop.
Save kmandov/70be1f3b2648ad2be1cdf1feb5afbb4d to your computer and use it in GitHub Desktop.
MapboxGL & D3.js - polygon

Example demonstrating the use of d3 v4 and mapbox-gl-js

<!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>
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment