更改 XYZ 图层的源 url 并重新绘制 layer/map?

Changing Source url of a XYZ layer and redrawing the layer/map?

我想更改我的 ol3 地图源的 url。我已经尝试使用诸如 map.set 或 map.getlayers().set 之类的东西,但我似乎无法找到访问源对象的方法。这是代码:

function init() {
    var map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection: 'PIXELS',
                    tileGrid: mapTileGrid,
                    url: loc
                })
            })
        ],
        view: new ol.View({
            projection: ol.proj.get('PIXELS'),
            extent: mapExtent,
             maxResolution: mapTileGrid.getResolution(0)
             })
        });

map.getView().fit(mapExtent, map.getSize());
    console.log(map.get("layergroup").get("layers").get("url"));
    map.get("layergroup").get("layers").set("url",loc);
}

有什么方法可以更改 url 属性 并重新加载图层?

我还尝试使用 setSource 函数,如下面的答案:here 但它似乎不起作用(无法设置未定义的来源)。

尝试以下方法

function init() {
    var map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Tile({
                source: new ol.source.XYZ({
                    projection: 'PIXELS',
                    tileGrid: mapTileGrid,
                    url: loc
                })
            })
        ],
        view: new ol.View({
            projection: ol.proj.get('PIXELS'),
            extent: mapExtent,
             maxResolution: mapTileGrid.getResolution(0)
             })
        });

map.getView().fit(mapExtent, map.getSize());
//get alll the layers exist on your map
var layers = map.getLayers();
//lets assume you want to set the url for the first layer found
layers[0].getSource().setUrl(loc); 
}