zooming in to vector layer when i click a URL

2019-09-11 18:56发布

问题:

I have a WFS layer in my map. I have buildings in the layer with building_id as an attribute along with other many attributes. I have coordinates too in my layer.

I have a URL: http://localhost:8080/geoserver/wfs?service=wfs&version=1.0.0&request=getfeature&typename=topp:buildings&CQL_FILTER=id='bb21'

How can I use this URL to zoom my map to that building?

Any ideas?

AJ

================updated here ===============

$.ajax({
    url: 'http://localhost:8080/geoserver/wfs?service=wfs&version=1.0.0&request=getfeature&typename=genesis:Building_WGS&CQL_FILTER=HOUSE_NO=%271436%27',
    xhrFields: {
        withCredentials: true
    },
    success: function(data) {
        var te = new ol.format.GML2();

        var a = te.readFeatures(data)
        var feature = new ol.Feature(a);
        //console.log(test1);
        var geom = feature.get("HOUSE_NO");
        var view = map.getView();
        //view.fit(geom, map.getSize());
        console.log(geom);
    }   
});

回答1:

First, you'll have to query the url using an ajax request. Many JavaScript libraries support simple ways to make such request, such as jQuery: http://api.jquery.com/jquery.ajax/

Then, upon receiving the request response, you'll have to read the result. If you're using WFS, then your response should be in GML. OL3 has a format for GML 2 and 3:

  • http://openlayers.org/en/v3.9.0/apidoc/ol.format.GML2.html
  • http://openlayers.org/en/v3.9.0/apidoc/ol.format.GML3.html

Both have a readFeatures method you can use to transform your response into an array of features, i.e. into instances of ol.Feature. Then you can loop in those features and get their geometry and fit the map to that geometry.

var geom = feature.getGeometry();
var view = map.getView();
view.fit(geom, map.getSize());