如何更改打开的图层拼贴源?

时间:2017-09-04 07:13:14

标签: javascript openlayers

我需要更改openlayer的图层来源(使用开放天气api)。目前我使用以下代码但没有成功。

let layer = this.map.getLayers().getArray()[2]
layer.setSource(forecastLayer)
你告诉我我做错了吗? 更新数据源的正确方法是什么?

  renderMapOpenLayer () {
    let geo = this.props.geo

    // render marker vector
    let markerFeature = new ol.Feature({
      geometry: new ol.geom.Point(ol.proj.transform([-72.0704, 46.678], 'EPSG:4326', 'EPSG:3857')) // TODO // take lat long from openweather api which should be sotred in the state
    })

    let markerSource = new ol.source.Vector({
      features: [markerFeature]
    })

    let markerStyle = new ol.style.Style({
      image: new ol.style.Icon(({
        anchor: [0, 0],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 0.75,
        src: 'assets/pin.svg'
      }))
    })

    let markerLayer = new ol.layer.Vector({
      source: markerSource,
      style: markerStyle
    })

    // render OpenStreetMap tile server
    var tileLayer = new ol.layer.Tile({
      source: new ol.source.OSM()
    }, new ol.layer.Vector({
      source: new ol.source.Vector({ features: [], projection: 'EPSG:4326' })
    }))

    // render cloud tile
    let cloudLayer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: api.mapTemperature()
      })
    })

    let forecastLayer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: api.forecast()
      })
    })

    setTimeout(function () {
      let layer = this.map.getLayers().getArray()[2]
      layer.setSource(forecastLayer)
    }.bind(this), 3000)

    // create map
    this.map = new ol.Map({
      target: 'map',
      layers: [
        tileLayer,
        markerLayer,
        cloudLayer
      ],
      view: new ol.View({
        center: ol.proj.transform(geo, 'EPSG:4326', 'EPSG:3857'),
        zoom: 4
      })
    })
  }

1 个答案:

答案 0 :(得分:0)

layer.setSource应该可以解决问题。

    function onClick() {
        layer.setSource(xyz2);
    }

    var xyz1 = new ol.source.XYZ({
        url: 'https://server.arcgisonline.com/ArcGIS/rest/services/' +
              'Demographics/USA_Percent_Over_64/MapServer/tile/{z}/{y}/{x}'
    })
    var xyz2 = new ol.source.XYZ({
        url: 'https://server.arcgisonline.com/ArcGIS/rest/services/' +
              'Demographics/USA_Percent_Under_18/MapServer/tile/{z}/{y}/{x}'
    })

    var layer = new ol.layer.Tile({
        source: xyz1
    });

    var map = new ol.Map({
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            }),
            layer
        ],
        target: 'map',
        view: new ol.View({
            center: ol.proj.fromLonLat([0, 0]),
            zoom: 3
        })
    });

这是一个有效的例子:

layer.setSource Example