使用openlayer在平铺背景上显示kml文件的基本脚本;我刚刚从版本2切换到4.65,如何缩放到kml几何体的极限(这里是“矢量”)?
var wmsSource = new ol.source.TileWMS({
url: "https://sedac.ciesin.columbia.edu/geoserver/wms",
params: {"LAYERS": "other:wwf-terrestrial-biomes", "TILED": true},
serverType: "geoserver"
});
var wmsLayer = new ol.layer.Tile({
opacity: 0.15,
visible: true,
source: wmsSource
});
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
url: "kml_file.kml",
format: new ol.format.KML()
})
});
var map = new ol.Map({
target: "map-canvas",
layers: [wmsLayer, vector],
controls: ol.control.defaults().extend([
new ol.control.ScaleLine({units: "metric"}),
new ol.control.FullScreen()
]),
view: new ol.View({
center: ol.proj.transform([37.41, 8.82], "EPSG:4326", "EPSG:3857"),
zoom: 3
})
});
我想替换zoom: 3
并让地图居中并扩展到kml限制?
注意:我将kmllayer.events.register("loadend", kmllayer, function(evt){map.zoomToExtent(kmllayer.getDataExtent())});
与OpenLayers2 ...
答案 0 :(得分:1)
以下应该做你想做的事
var vectorSource = vector.getSource();
vectorSource.once('change', function(e){
if (vectorSource.getState() === 'ready') {
var extent = vectorSource.getExtent();
map.getView().fit(extent);
}
});
解决方案主要改编自How to get the extent of a GeoJSON vector source?(更改了变量名称&删除了map.getView().fit
中的第二个参数(旧时需要,现在是可选的,大部分时间都不需要,就像这里一样)
答案 1 :(得分:0)
好的,我需要将kml源声明为单独的new ol.source.Vector
变量,此处为vectorSource
,并从此变量中读取.getExtent()
,而不是ol.layer.Vector
:< / p>
var wmsSource = new ol.source.TileWMS({
url: "https://sedac.ciesin.columbia.edu/geoserver/wms",
params: {"LAYERS": "other:wwf-terrestrial-biomes", "TILED": true},
serverType: "geoserver"
});
var wmsLayer = new ol.layer.Tile({
opacity: 0.15,
visible: true,
source: wmsSource
});
var vectorSource = new ol.source.Vector({
url: "'.$kml_f.'",
format: new ol.format.KML()
});
var vector = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
target: "map-canvas",
layers: [wmsLayer, vector],
controls: ol.control.defaults().extend([
new ol.control.ScaleLine({units: "metric"}),
new ol.control.FullScreen()
]),
view: new ol.View({
center: ol.proj.transform([37.41, 8.82], "EPSG:4326", "EPSG:3857"),
zoom: 4,
})
});
vector.once("change", function(e){
var extent = vectorSource.getExtent();
map.getView().fit(extent);
});
感谢您的帮助!