I am trying to showcase the topoJSON
on a leaflet
map using d3
. To achieve this, I am following an example on GitHub available at this link.
Here is the code I have extracted from the GitHub example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3 Test</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
<script type="text/javascript" src="https://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id="map" style="width:600px; height:600px;"></div>
<script>
var map = new L.Map("map", {
center: [37.8, -96.9],
zoom: 4
})
.addLayer(new L.TileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"));
var svg = d3.select(map.getPanes().overlayPane).append('svg');
var g = svg.append('g').attr('class', 'leaflet-zoom-hide');
d3.json("pathToTopotJson", function(error, collection) {
if (error) throw error;
console.log(collection)
var bounds = d3.geo.bounds(topojson.feature(collection, collection.objects.collection));
var path = d3.geo.path().projection(projectPoint);
var feature = g.selectAll('path')
.data(topojson.feature(collection, collection.objects.collection).features)
.enter()
.append('path');
map.on('viewreset', reset);
reset();
// Reposition the SVG to cover the features.
function reset() {
var bottomLeft = projectPoint(bounds[0]),
topRight = projectPoint(bounds[1]);
svg.attr('width', topRight[0] - bottomLeft[0])
.attr('height', bottomLeft[1] - topRight[1])
.style('margin-left', bottomLeft[0] + 'px')
.style('margin-top', topRight[1] + 'px');
var translation = -bottomLeft[0] + ',' + -topRight[1];
g.attr('transform', 'translate(' + -bottomLeft[0] + ',' + -topRight[1] + ')');
feature.attr('d', path);
}
// Use Leaflet to implement a D3 geographic projection.
function projectPoint(x) {
var point = map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
return [point.x, point.y];
}
})
</script>
The topoJSON
is being displayed, but with unexpected Polygons/Lines:
https://i.sstatic.net/7KoIW.png
When I display the JSON
, the polygons/lines are not visible:
https://i.sstatic.net/rHpim.png
What could be causing this issue with the topoJSON
? Is it an error in my code or during the conversion process?