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();
上述代码将在获取我想要映射的数据后向leaflet地图添加点。问题在于,当我放大地图时,所有点仍保持在原来的位置,而地图背景则变化了视角。除了初始视图外,这些点实际上并未“固定”在正确的位置。我知道这与我更新视图的方式有关,但我一直没有能够解决它。请帮忙!先谢谢。