0

下面的代码使用地图中心的绝对位置,但我想根据从 KML 文件中引入的矢量图层特征来设置中心 - 这可能吗?我看过 getCentroid 但语法不正确?

map = new OpenLayers.Map("Map");
var mapnik = new OpenLayers.Layer.OSM();
//Set centre position converting from WGS to Mercator
var wgs84 = new OpenLayers.Projection("EPSG:4326");
var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
var toProjection   = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position       = new OpenLayers.LonLat(4.891280,52.373690).transform( fromProjection, toProjection);

var layer = new OpenLayers.Layer.Vector("vectorlayer", {
    projection: wgs84,
    strategies: [new OpenLayers.Strategy.Fixed()],
    protocol: new OpenLayers.Protocol.HTTP({
        url: "kmlfile.kml",   //<-- relative or absolute URL to your .osm file
        format: new OpenLayers.Format.KML()
    }),
    styleMap: new OpenLayers.StyleMap({
      "default": {
            //pointRadius: "${radius}",
            fillColor: "blue",
            fillOpacity: 0.1,
            strokeColor: "#5555ff",
            strokeWidth: 2,
            strokeOpacity: 0.8
       }
        ,
      "select": {
          fillColor: "#8aeeef",
          strokeColor: "#32a8a9"
      }
    })
});

map.addLayers([mapnik, layer]);

map.addControl(new OpenLayers.Control.LayerSwitcher());

var scaleline = new OpenLayers.Control.ScaleLine();
map.addControl(scaleline);


//Set centre of map and zoom level
map.setCenter(position, 10 );
4

1 回答 1

0

试试这个(其中 layer 是基于您的代码的向量):

var bounds = layer.geometry.bounds;
map.zoomToExtent(bounds);

或者

var bounds = layer.geometry.bounds;
map.setCenter(bounds.getCenterLonLat());
于 2013-05-22T09:47:18.453 回答