我在D3中实现了一张地图。我现在想要添加缩放按钮来放大和缩小地图,例如this
我的实施:
<head>
<title>test</title>
<script src="jquery.min.js"></script>
<script src="d3.min.js"></script>
<script src="topojson.min.js"></script>
</head>
<body>
<div id="zoomBtn">
<input class="zoomBtn" rel="out" type="button" value="-" />
<input class="zoomBtn" rel="in" type="button" value="+" />
</div>
<div id="map"></div>
<style>
#zoomBtn{ position: absolute; top: 10px; left: 10px; }
#map{ width: 960px; height: 500px; }
</style>
<script>
var PHM = (function() {
var options = {
mapScope: 'states',
minZoomLevel: 1,
maxZoomLevel: 8
};
var svg, g, projection, path, zoom, mapFeatures;
var width, height;
function initMap() {
width = $('#map').width();
height = $('#map').height();
d3.json("states.json", function(json) {
//the svg element
svg = d3.select("#map").append("svg")
.attr("width", width)
.attr("height", height);
g = svg.append("g");
projection = d3.geo.mercator()
.translate([-1000,700])
.scale(1000);
mapFeatures = topojson.feature(json, json.objects[(options.mapScope == 'world') ? 'world' : 'india']);
var mapItems = g.selectAll("g").data(mapFeatures.features);
path = d3.geo.path()
.projection(projection);
var b = path.bounds(mapFeatures);
var scale = .90 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height);
var translate = [(width - scale * (b[1][0] + b[0][0])) / 2, (height - scale * (b[1][1] + b[0][1])) / 2];
projection
.scale(scale)
.translate(translate);
mapItems.enter().append("path")
.attr("class", "country")
.attr("d", path)
.attr("id", function(d,i) { return d.id; })
.attr("title", function(d,i) { return d.properties.name; })
.style('stroke-width', 1)
.style('stroke', '#ccc');
d3.behavior.zoom();
zoom = d3.behavior.zoom()
.scaleExtent([options.minZoomLevel, options.maxZoomLevel])
.on("zoom", zoomed);
svg.call(zoom).call(zoom.event);
});
}
function initApp() {
initMap();
initAppControls();
}
function initAppControls() {
$('.zoomBtn').on('click', function(e){
zoomBtn($(this).attr('rel'));
e.preventDefault();
})
}
function zoomBtn(action) {
var currentZoom = zoom.scale();
if( action == 'in' ){
if(currentZoom < options.maxZoomLevel){
var newScale = Math.floor(currentZoom) + 1;
var b = path.bounds(mapFeatures);
var t = [(width - newScale * (b[1][0] + b[0][0])) / 2, (height - newScale * (b[1][1] + b[0][1])) / 2];
console.log(newScale);
console.log(t);
zoom.scale(newScale)
.translate(t)
.event(svg);
}
}else{
if(currentZoom > options.minZoomLevel){
var newScale = Math.floor(currentZoom) - 1;
var b = path.bounds(mapFeatures);
var t = [(width - newScale * (b[1][0] + b[0][0])) / 2, (height - newScale * (b[1][1] + b[0][1])) / 2];
console.log(newScale);
console.log(t);
zoom.scale(newScale)
.translate(t)
.event(svg);
}
}
}
return {
init: function(){
initApp();
}
}
})();
</script>
</body>
</html>
states.json 是包含有关地图数据的本地json文件。 所有包含的js文件都存在于本地。
我尝试过托管代码。它仍然不起作用,所以问题出在其他地方!
但这根本不会渲染地图。只显示缩放按钮。