2017-07-07 75 views
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 &copy; <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點保持在傳單地圖上的正確位置?

回答

相關問題