我希望将 Mapbox map 放入 X,Y 大小的容器中。然后我需要一个 slider ,当调整时,它会同时调整 div 的大小并以反比例缩放 map 。这听起来像是简单地放大 map ,但期望的效果是 div 看起来保持相同的大小,但 map 的更宽部分进入视野,同时在 map 上保持相同的缩放级别,实际上我正在扩大 map 的视口(viewport),但保持容器在页面上的视口(viewport)大小相同。
我对实现的最初想法是这样的:
#map{ width: 250px; height: 250px; }
然后 slider 输入值 .5,我们将执行 变换:比例(0.5); 同时将div增加到500px,500px
如果有人有一些想法,我已经在这里创建了测试平台:http://jsfiddle.net/cdubbs/91uj9ce7/
这样的事情有可能吗?或者是否有其他方法可以做到这一点(它是否会执行得更快或更广泛地兼容)?
最佳答案
我不会撒谎...这个解决方案有点“hack”-y,但它确实有效。
更新:现在适用于 Firefox 和 IE(仅在 IE11 上测试过)
演示: http://jsfiddle.net/hopkins_matt/91uj9ce7/13/
HTML:
<div id="map" style="width: 250px; height: 250px;"></div>
<input type="range" min="10" max="100" value="100" class="scale" step="1" oninput="scaleMap(value)" onchange="scaleMap(value)" id="scale">
<output for="fader" id="percentage">100</output>
JS:
mapboxgl.accessToken = '* insert access token *';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'https://www.mapbox.com/mapbox-gl-styles/styles/outdoors-v7.json', //stylesheet location
center: [40, -74.50], // starting position
zoom: 9 // starting zoom
});
function scaleMap(percentage) {
document.querySelector('#percentage').value = percentage;
var mapDiv = document.getElementById("map");
var initialWidth = mapDiv.offsetWidth;
var initialHeight = mapDiv.offsetHeight;
var mapCanvas = document.getElementsByTagName("canvas");
function divSize(multiplier) {
return (100 / percentage) * multiplier;
}
var mapScale = (percentage / 100);
mapDiv.style.width = divSize(initialWidth) + "px";
mapDiv.style.height = divSize(initialHeight) + "px";
mapCanvas[0].style.width = divSize(initialWidth) + "px";
mapCanvas[0].style.height = divSize(initialHeight) + "px";
mapCanvas[0].width = divSize(initialWidth);
mapCanvas[0].height = divSize(initialHeight);
map.resize();
mapCanvas[0].style.transform = "scale(" +mapScale+")";
mapCanvas[0].style.marginLeft = (((divSize(initialWidth) - initialWidth) / 2) * -1) + "px";
mapCanvas[0].style.marginTop = (((divSize(initialHeight) - initialHeight) / 2) * -1) + "px";
document.getElementById("map").style.width = initialWidth + "px";
CSS:
#map {
overflow: hidden;
position:relative;
}
#map div canvas {
padding: 0;
margin: auto;
display: block;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
关于javascript - 在转换内容的同时调整容器的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32058740/