2
var map = L.map('mapid').setView([10.0, 15.0], 2);
L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/light-v9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic2FidW1hZm9vIiwiYSI6ImNqMWE3cnlqcTA5dncyd216YjI0bnY4dGEifQ.fgmXgmkvialdBd3D405_BA', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
maxZoom: 18,
id: 'mapbox.streets',
accessToken: 'pk.eyJ1Ijoic2FidW1hZm9vIiwiYSI6ImNqMWE3cnlqcTA5dncyd216YjI0bnY4dGEifQ.fgmXgmkvialdBd3D405_BA'
}).addTo(map);
L.svg().addTo(map);
var svg = d3.select(map.getPanes().overlayPane).select('svg');
var g = svg.append('g').attr('class', 'leaflet-zoom-hide');
const URL = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=200'
function getEarthquakeData() {
fetch(URL)
.then((results) => {
return results.json();
})
.then((result) => {
function projectPoint(x,y) {
var point = map.latLngToLayerPoint(new L.LatLng(y,x));
this.stream.point(point.x, point.y);
}
var transform = d3.geoTransform({point: projectPoint}),
path = d3.geoPath().projection(transform);
function applyLatLngToLayer(d){
var y = d.geometry.coordinates[1];
var x = d.geometry.coordinates[0];
return map.latLngToLayerPoint(new L.LatLng(y,x));
}
// console.log(result.features);
// result.features.forEach(function(d) {
// d.LatLng = new L.LatLng(d.geometry.coordinates[1],
// d.geometry.coordinates[0])
// });
var circle = g.selectAll('circle')
.data(result.features)
.enter().append('circle')
.style('fill','darkred')
.attr('r', 2)
.attr('opacity',0.5);
function update() {
circle.attr("transform",
function(d) {
return "translate("+
applyLatLngToLayer(d).x+","+
applyLatLngToLayer(d).y+")";
});
var bounds = path.bounds(result),
topLeft = bounds[0],
bottomRight = bounds[1];
svg.attr("width", bottomRight[0] - topLeft[0])
.attr("height", bottomRight[1] - topLeft[1])
.style("left", topLeft[0] + "px")
.style("top", topLeft[1] + "px");
g.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");
}
map.on('viewreset', update);
update();
})
}
getEarthquakeData();
上述代码会在获取我感兴趣的映射数据后,为传单映射添加点。问题是,当我放大地图时,地图背景更改视图时,所有点都保持在同一位置。除了开放视图之外,这些点实际上并没有“粘贴”到任何视图中的正确位置。我知道这与我更新视图的方式有关,但我一直无法弄清楚。请帮忙!提前致谢。如何在放大缩小时将d3 svg点保持在传单地图上的正确位置?
非常感谢! – user2097478