javascript - OpenLayers:单击更改图层源

标签 javascript html maps openlayers

看起来很简单,但我想不通。标有“2005”、“2010”和“2015”的按钮应该将显示的图层更改为分配给相应变量的图层。现在, map 显示得很好,缩放按钮可以正常工作,但其他按钮不会任何东西。层彼此不同,因此当层被切换时应该有一个可观察到的变化。感谢您的评论和帮助。

代码如下:

<button id = "zoom" type="button">Zoom to Extent</button>   
<button id = "2005" type="button">2005</button> 
<button id = "2010" type="button">2010</button> 
<button id = "2015" type="button">2015</button>

<div style="width:100%; height:100%" id="map"></div>
<script defer="defer" type="text/javascript">
    var map = new OpenLayers.Map('map');
    var GWP2005 = new OpenLayers.Layer.WMS(
        "Population Density",
        "http://sedac.ciesin.columbia.edu/geoserver/wms",
        {layers: 'gpw-v3:gpw-v3-population-density-future-estimates_2005'}
    );
    var GWP2010 = new OpenLayers.Layer.WMS(
        "Population Density",
        "http://sedac.ciesin.columbia.edu/geoserver/wms",
        {layers: 'gpw-v3:gpw-v3-population-density-future-estimates_2010'}
    );
    var GWP2015 = new OpenLayers.Layer.WMS(
        "Population Density",
        "http://sedac.ciesin.columbia.edu/geoserver/wms",
        {layers: 'gpw-v3:gpw-v3-population-density-future-estimates_2015'}
    );
    map.addLayers([GWP2005]);
    map.zoomToMaxExtent();

    var but_zoom = document.getElementById("zoom");
    but_zoom.addEventListener("click", function(){map.zoomToMaxExtent()}, false);
    var but_2005 = document.getElementById("2000");
    but_2005.addEventListener("click", function(){map.addLayers([GWP2005]); map.zoomToMaxExtent;}, false);
    var but_2010 = document.getElementById("2010");
    but_2010.addEventListener("click", function(){map.addLayers([GWP2010]); map.zoomToMaxExtent;}, false);
    var but_2015 = document.getElementById("2015");
    but_2015.addEventListener("click", function(){map.addLayers([GWP2015]); map.zoomToMaxExtent;}, false);
</script>

最佳答案

您可以在初始化时将所有图层一次添加到 map 中,并为它们赋予属性“isBaseLayer: true”。这使得它们相互排斥,您可以通过在 map 上调用 setBaseLayer 在它们之间切换。

var map = new OpenLayers.Map('map');
var GWP2005 = new OpenLayers.Layer.WMS(
        "Population Density",
        "http://sedac.ciesin.columbia.edu/geoserver/wms",
        { layers: 'gpw-v3:gpw-v3-population-density-future-estimates_2005' },
        { isBaseLayer: true }
    );

map.addLayers([
    GWP2005,
    // other layers
]);

var but_2005 = document.getElementById("layer-2005");
but_2005.addEventListener("click", function(){ 
     map.setBaseLayer(GWP2005); 
     map.zoomToMaxExtent(); }, 
false);

关于javascript - OpenLayers:单击更改图层源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26081156/

相关文章:

javascript - 如何避免在 React 中额外包装 <div>?

javascript - 使用下划线 groupby 按多个属性对一组对象进行分组

html - 自动拉伸(stretch)表格单元格 div css

r - 传单标签重叠修复 - leaflet::addMarkers

找到地球上 100 个最长且陡度超过 30 度的斜坡的算法?

ios - 使用 MapKit Swift 在两个坐标之间绘制路径

JavaScript DOM 遍历

javascript - 如何进一步抽象具有太多重复逻辑的指令

javascript - 使用 window.open() 打开文件时传递 url 参数(从 ColdFusion 页面)

javascript - 如何确定单选按钮组中的特定单选按钮是否被选中?