OpenLayers:点击更改图层来源

时间:2014-09-28 02:54:07

标签: javascript html maps openlayers

看起来很简单,但我无法弄清楚。标有“2005”,“2010”和“2015”的按钮应该将显示的图层更改为分配给相应变量的按钮。现在,地图显示正常,缩放按钮完成其工作,但其他人不做任何。图层彼此不同,所以当图层被切换时应该有一个可观察到的变化。感谢您的评论和帮助。

以下是代码:

<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>

1 个答案:

答案 0 :(得分:2)

您可以在init处立即将所有图层添加到地图中,并为其提供属性&#34; isBaseLayer:true&#34;。这使它们互斥,您可以通过在地图上调用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);