Transform the AJAX response into an OL3 GML Layer

I've been experimenting with OpenLayers3 and encountering some difficulty with a getfeatureinfo request. I've been attempting to use ajax for this purpose and convert the response into a GML layer similar to what could be done in OpenLayers2.

Here's the code snippet I'm currently using:

$.ajax({url: GeoServerURL,
     data: params,
     type: 'POST',
     dataType: 'text',
     success: function (response) {
         console.log('Success!');
         var gmlLayer = new ol.format.GML({
             featureNS: 'http://www.swansea.gov.uk/',
             featurePrefix: 'ccs',
             geometryName: 'geom',
             extractAttributes: true
        });
        var results = gmlLayer.writeFeatures(response.responseText);
        if (results.length === 0) {
            return;
        }
    }
});

I am aware that the ajax call returns the correct response, and in openlayers 2, I would have used the following command:

results = gmlLayer.read(response.responseText);

This is the XML response from the getFeatures request:

<?xml version="1.0" encoding="UTF-8"?>
<!-- rest of the XML content goes here -->

My goal is to parse the response and display it as a popup while maintaining the structure as a GML feature.

Answer №1

Here is the JSON-formatted request that works effectively in ol3.

map.on('singleclick', function(evt) {

    bounds = map.getView().calculateExtent(map.getSize())
    var params = {
        request: "GetFeatureInfo",
        exceptions: "application/vnd.ogc.se_xml",
        bbox: bounds.join(','),
        x: parseInt(evt.pixel[0], 10),
        y: parseInt(evt.pixel[1], 10),
        info_format: 'application/json',
        query_layers: getLayers(),
        feature_count: 70,
        buffer: 5,
        srs: 'EPSG:27700',
        layers: getLayers(),
        styles: '',
        width: map.getSize()[0],
        height: map.getSize()[1]
    };
    $.ajax({url: GeoServerURL,
        data: params,
        type: 'POST',
        dataType: 'json',
        success: function (response) {
            //I couldn't get the response to be read as a GML file so changed it to geoJSON 
            Results = response;
            if (response.features.length === 0) {
                return;
            }

            setPopup(response,evt,0);
        }
    });
});

Answer №2

In the case that the server is Geoserver (I am making an assumption here), simply include

&outputFormat=application/json
in the URL to receive the response in GeoJson format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pagination and asynchronous deletion with will_paginate

Currently, I have a list of resources that are displayed on a paginated list using the will_paginate gem. I haven't made any customizations yet, here is how my view looks: <ul> <%= render :partial => "item_li", :collection => @items%& ...

Unable to retrieve custom date picker value with React Antd

I have implemented a custom datepicker for entering dates in the 'MMDD' or 'MMDDYY' format. The date value is stored in state and used in the datepicker component as a controlled component. However, upon form submission, the datepicker ...

Repeating an AJAX request overlooks the success callback function

I am facing a challenge in refreshing an AJAX call when the token expires. Although everything seems to be working fine with the implementation of ajaxSetup, I noticed that the request is not triggering the success callback as expected. $.ajax({ url: ...

Using $route to obtain URL parameters

I am faced with the challenge of passing the last parameter from the following URL to a $http.get request in my Angular application. http://myurl.dev/users/32 However, I am struggling to figure out how to pass the 32 as the id. Here is what I have tried ...

Using ES6 syntax, ignite the React function

Below is the code snippet provided: class Seismo extends Component { constructor(props) { super(props); this.state = { news: "" } this.updateNews = this.updateNews.bind(this) } updateNews = () => { console.log('te ...

"Troubleshooting: ngForm.controls returning undefined value in Angular application

Trying to test this HTML code in Angular: <form name="formCercarUsiari" #formCercarUsuari="ngForm" class="tab-content"> <input #inputNif class="form-control input-height" maxlength="100" type="text" placeholder="Indiqui NIF" name="nif" i18n-pla ...

Tips for creating a sequence pattern in JavaScript or jQuery resembling 12345-1234567-8

I am looking to adjust this code so that a hyphen "-" is automatically inserted after every 5 characters, and then again after every 7 characters. Currently, the code only inserts a hyphen after every 5 characters. <html> <head> <scri ...

Using AngularJS to interact with neighboring DOM elements

Imagine a scenario where there is a div containing 5 img elements. When one of these img elements is hovered over, the goal is to change the class of all the elements on its left side. <div id="stars"> <img src="star.png" data-rating="1" ng- ...

Enhancing a JQuery Element to Suit Your Needs

Is it recommended to enhance a JQuery element with custom methods? For example: var b = $("#uniqueID"); b.someMethod = function(){}; Additional Information Let me explain further, I am developing a JavaScript application that binds JSON data to local J ...

utilizing mongoose populate for displaying the author

One of the features on my website allows users to add notices, and I want the page to display the author of each notice. const notices = await Notice.findById(id).populate('author'); When I access this route, I can successfully log the authors o ...

Yet another error encountered: "Headers cannot be set after they have already been sent to the client" when submitting the form

Whenever I try to submit text to a single-field form on my node.js server, I encounter the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11) ...

Difficulty Sorting Dates in Material UI DataGrid

I have a DataGrid in Material UI, and one of my columns displays dates. Following the guidance from the Material UI documentation, I have set the type to "date" in the column array: { field: "submittedAt", headerName: "Submitted", minWidth: 150, flex: 2, t ...

Angular Directives in Error

Help needed with creating a custom directive in Angular. Seeking guidance :) I am trying to display the content from 'directive.html' within the 'app-info' directive. The code functions properly without the directive, indicating a mist ...

Encountering a 404 Error on all routes except the home page when working with the Express Application Generator

While working on developing a day planner, I encountered an issue with the routes. I am consistently receiving a 404 error for any route other than the main Home page route (index or "/"). Below is the content of the app.js file: var express = require(&ap ...

Dividing points in half at the top and bottom edges in a chart using chartjs

https://i.sstatic.net/AfosF.png Upon observation of the provided image, it can be seen that the points are halved when they reach the top or bottom edges, specifically when the data points are 1 or 5 in this context. Various attempts were made to address ...

Incorporating a JavaScript script into my Angular 7 project

My project requires me to incorporate the "Loadingbar.js" library into one of my pages. You can find this library here: . Initially, I inserted the CSS code into my global "style.css" file. I started by placing the script in my index.html file: <script ...

Transforming identical elements in an arrayt array into distinct elements without eliminating any element in Javascript

Looking for a solution to remove duplicates from an array? You may have come across using track by $index in ng-repeat of angularjs, but you want to stick with a regular ng-repeat. Here's the scenario: Array=[ { name:'john',salary:& ...

Enhance your online shopping experience with a personalized touch by incorporating an Ajax add to cart button on

Currently, I am working on customizing the add to cart button on a single product page. After implementing an ajax call solution from LoicTheAztec's post here, I have successfully added the feature. The code works perfectly fine, but now I am faced w ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...

Selecting hidden elements in jQuery with the exception of

Typically, jQuery Validation does not validate hidden elements: ignore (default: ":hidden") Type: Selector Elements to exclude during validation, filtering them out. jQuery’s not-method is utilized, therefore any valid selector for not() can be used ...