您好,您可以监听vector图层的featuresadded事件然后触发zoomTo事件。出现这个报错应该是和地图、图层初始化有关系。在官网范例中如果是在addData()中添加zoom地图的代码默认执行的时候也会报这个错误,但是删除数据重新加载数据后就是正常的了
在官网范例中参考这段代码,可以看到效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title data-i18n="resources.title_vectorLayerData"></title>
<style type="text/css">
body {
margin: 0;
overflow: hidden;
background: #fff;
width: 100%;
height: 100%
}
#map {
position: absolute;
width: 100%;
height: 100%;
}
#toolbar {
position: absolute;
top: 50px;
right: 10px;
text-align: center;
z-index: 100;
border-radius: 4px;
}
</style>
</head>
<body>
<div id="toolbar" class="panel panel-primary">
<div class='panel-heading'>
<h5 class='panel-title text-center' data-i18n="resources.text_basicVectorLayerData"></h5></div>
<div class='panel-body content'>
<input type="button" class="btn btn-default" data-i18n="[value]resources.text_input_value_addData" onclick="addData()"/>
<input type="button" class="btn btn-default" data-i18n="[value]resources.text_input_value_removeData" onclick="removeData()"/>
</div>
</div>
<div id="map"></div>
<script type="text/javascript" include="bootstrap,widgets" src="../js/include-web.js"></script>
<script type="text/javascript" exclude="iclient-classic" src="../../dist/classic/include-classic.js"></script>
<script type="text/javascript">
var map, layer, dataAdded = false,
host = window.isLocal ? window.server : "https://iserver.supermap.io",
url = host + "/iserver/services/map-world/rest/maps/World";
init();
function init() {
map = new SuperMap.Map("map", {
controls: [
new SuperMap.Control.Zoom(),
new SuperMap.Control.Navigation(),
]
});
map.addControl(new SuperMap.Control.LayerSwitcher(), new SuperMap.Pixel(42, 80));
layer = new SuperMap.Layer.TiledDynamicRESTLayer("World", url, null, {maxResolution: "auto"});
layer.events.on({"layerInitialized": addLayer});
vector = new SuperMap.Layer.Vector("vector");
vector.events.on({'featuresadded':panTo})
}
function panTo(){
console.log(1);
var bounds = new SuperMap.Bounds(-150,25.857,-110,54.142);
map.zoomToExtent(bounds,{closest:true});
}
function addLayer() {
map.addLayers([layer, vector]);
//显示地图范围
map.setCenter(new SuperMap.LonLat(0, 0), 0);
}
function addData() {
widgets.alert.clearAlert();
if (!dataAdded) {
vector.removeAllFeatures();
//六边形
var points2 = [
new SuperMap.Geometry.Point(-120, 54.142),
new SuperMap.Geometry.Point(-110, 40),
new SuperMap.Geometry.Point(-120, 25.857),
new SuperMap.Geometry.Point(-140, 25.857),
new SuperMap.Geometry.Point(-150, 40),
new SuperMap.Geometry.Point(-140, 54.142)
],
linearRings = new SuperMap.Geometry.LinearRing(points2),
region = new SuperMap.Geometry.Polygon([linearRings]);
var polygonVector = new SuperMap.Feature.Vector(region);
vector.addFeatures([ polygonVector]);
dataAdded = true;
} else {
widgets.alert.showAlert(resources.msg_loadedData, true, 240);
}
}
function removeData() {
widgets.alert.clearAlert();
dataAdded = false;
vector.removeAllFeatures();
vector.refresh();
}
</script>
</body>
</html>