Я столкнулся со многими примерами создания объекта JSON из строки JSON с помощью метода JSON.parse(string), но как загрузить функции этого объекта при использовании JSON.parse мне не ясно. Например, копирование и вставка текста по ссылке ниже (json file: canada.topo.json), у меня есть следующий код:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke: white;
stroke-width: 0.25px;
fill: grey;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script>
var json = "jsonfile"
jobj = JSON.parse(json)
var width = 960,
height = 1160;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
//what to do next is my problem
//A simple way to just project a map typically is with the following, which fails in this case:
function(error, us) {
svg.append("path")
.data(jobj)
//How do I load the features from the jobj object??
.feature(us, us.objects.Canada).features
.attr("d", d3.geo.path().projection(d3.geo.mercator()));
}
//As a side point, this does not throw any errors, but nothing happens of course as there are no features
var svg = d3.select("body")
d3.select('.countries').selectAll('path')
.data(jobj)
svg.append("path")
.attr("d", d3.geo.path().projection(d3.geo.mercator()));
</script>
ВОПРОС: Как загрузить функции jobj в D3?
https://github.com/returnOfTheYeti/CanadaJSON/blob/master/canada.topo.json
https://github.com/returnOfTheYeti/CanadaJSON/blob/master/canada.topo.json эта ссылка, это ссылка на страницу github, а не на ваш json файл.
Вы должны использовать этот url- https://raw.githubusercontent.com/returnOfTheYeti/CanadaJSON/master/canada.topo.json. Вы можете получить этот url для любого файла, нажав кнопку "Raw".
Таким образом, с d3.json
метода d3.json
вы можете загрузить этот файл таким образом:
d3.json('https://raw.githubusercontent.com/returnOfTheYeti/CanadaJSON/master/canada.topo.json', function(data) {
console.log(data); // <= object with loaded data
console.log(topojson.feature(data, data.objects.Canada).features); // <= features
});
Проверьте этот jsFiddle.
Обновить:
В случае, когда json-строка хранится в некоторой переменной, вы можете получить функции и создать карту следующим образом:
var json = '...json string...';
var jobj = JSON.parse(json); // parse string
var width = 960,
height = 1160;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// get features array with topojson.feature method, bind it with .data method and create map
svg.selectAll("path")
.data(topojson.feature(jobj, jobj.objects.Canada).features)
.enter()
.append("path")
.attr("d", d3.geo.path().projection(d3.geo.mercator()));
Пример с вашими данными.
.features
и как его получить.