如何根据显示的点定义地图范围?



我使用d3.js在mapbox地图上叠加点,制作了以下地图。

我试图让地图缩放,使地图范围只包括d3标记(点)。

我认为伪代码应该是这样的:

//find the northernmost, easternmost, southernmost, westernmost points in the data
//get some sort of bounding box?
//make map extent the bounding box?

现有代码:

<div id="map"></div>
<script>
mapboxgl.accessToken = "YOUR_TOKEN";
var map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/streets-v9",
center: [-74.5, 40.0],
zoom: 9
});

var container = map.getCanvasContainer();
var svg = d3
.select(container)
.append("svg")
.attr("width", "100%")
.attr("height", "500")
.style("position", "absolute")
.style("z-index", 2);
function project(d) {
return map.project(new mapboxgl.LngLat(d[0], d[1]));
}
#Lat, long, and value
var data = [
[-74.5, 40.05, 23],
[-74.45, 40.0, 56],
[-74.55, 40.0, 1],
[-74.85, 40.0, 500],
];
var dots = svg
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("r", 20)
.style("fill", "#ff0000");
function render() {
dots
.attr("cx", function (d) {
return project(d).x;
})
.attr("cy", function (d) {
return project(d).y;
});
}
map.on("viewreset", render);
map.on("move", render);
map.on("moveend", render);
render(); // Call once to render
</script>

更新我找到了这段代码作为参考,链接在https://data-map-d3.readthedocs.io/en/latest/steps/step_03.html:

function calculateScaleCenter(features) {
// Get the bounding box of the paths (in pixels!) and calculate a
// scale factor based on the size of the bounding box and the map
// size.
var bbox_path = path.bounds(features),
scale = 0.95 / Math.max(
(bbox_path[1][0] - bbox_path[0][0]) / width,
(bbox_path[1][1] - bbox_path[0][1]) / height
);
// Get the bounding box of the features (in map units!) and use it
// to calculate the center of the features.
var bbox_feature = d3.geo.bounds(features),
center = [
(bbox_feature[1][0] + bbox_feature[0][0]) / 2,
(bbox_feature[1][1] + bbox_feature[0][1]) / 2];
return {
'scale': scale,
'center': center
};
}

然而,当我运行函数:

var scaleCenter = calculateScaleCenter(data);
console.log("scalecenter is", scaleCenter)

我得到错误:

path is not defined

此外,我似乎需要动态调整mapbox映射的centerzoom参数。我只是动态地设置这些值与calculateScaleCenter函数产生的值吗?

readthedocs示例代码错误地缺少了一段代码

你的javascript代码报告,你没有定义变量path之前使用它。您已经正确地从readthedocs中复制了它,但是您正在复制的代码包含一个遗漏。

幸运的是,在readthedocs版本的代码片段中,提到了堆栈溢出答案http://stackoverflow.com/a/17067379/841644这样可以提供更多的信息。

添加这些信息,或与您的情况相对应的类似内容,是否有助于解决您的问题?

var projection = d3.geo.mercator()
.scale(1);
var path = d3.geo.path()
.projection(projection);

最新更新