OpenLayers: real-time data display of objects from a list

When working with OpenLayers, I encountered an issue where my object was undefined and I couldn't retrieve the information I needed to display feature data on the map. Initially, I passed a list from the controller to my JSP file and attempted to use it in my JS file. However, that approach did not yield the desired results.

I then tried creating a JSON object and passing it instead, following an example at this link. The code snippet below shows part of my map.js script:

// Projections
// -----------
var sphericalMercatorProj = new OpenLayers.Projection('EPSG:900913');
var geographicProj = new OpenLayers.Projection('EPSG:4326');

// Vector layers
// -------------
// Sprinters: layer with different attributes.
var sprintersLayer = new OpenLayers.Layer.Vector('Sprinters (translated labels)', {
    styleMap: new OpenLayers.StyleMap({
        externalGraphic: 'resources/img/mobile-loc.png',
        graphicOpacity: 1.0,
        graphicWith: 16,
        graphicHeight: 26,
        graphicYOffset: -26
    })
});
sprintersLayer.addFeatures(getSprintersFeatures());

// Create map
// ----------
var map = new OpenLayers.Map({
    div: 'map',
    theme: null,
    projection: sphericalMercatorProj,
    displayProjection: geographicProj,
    units: 'm',
    numZoomLevels: 18,
    maxResolution: 156543.0339,
    maxExtent: new OpenLayers.Bounds(
        -20037508.34, -20037508.34, 20037508.34, 20037508.34
    ),
    controls: [
        new OpenLayers.Control.Attribution(),
        new OpenLayers.Control.Navigation(),
        new OpenLayers.Control.PanZoom(),
        new OpenLayers.Control.LayerSwitcher()
    ],
    layers: [
        new OpenLayers.Layer.OSM('OpenStreetMap', null),
        sprintersLayer
    ],
    center: new OpenLayers.LonLat(0, 0),
    zoom: 2
});
 

// Continued script...
<c:forEach items="${listFromController}" var="cor" varStatus="stat">
<c:choose>
<c:when test="${stat.count == 1}">
          <c:set var="chaine" value="${chaine}[[${cor.longitude},${cor.latitude},${cor.time}]" />
       </c:when>
       <c:otherwise>
          <c:set var="chaine" value="${chaine},[${cor.longitude},${cor.latitude},${cor.time}]" />
        </c:otherwise>
   </c:choose>
</c:forEach>
<c:set var="chaine" value="${chaine}]"/>

<div id="map" class="mws-panel-body"> </div>
<script src="resources/map.js"></script>

Answer №1

To effectively handle JSON objects while using the navigator, it is recommended to create a function for generating JSON objects and then utilizing jQuery ajax with it. In order to achieve this, we need to inject a bean into the spring context and define our JSON function:

<bean id="cnManager"  
    class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">  
  <property name="favorPathExtension" value="true"/>  
  <property name="ignoreAcceptHeader" value="true" />  
  <property name="defaultContentType" value="text/html" />  
  <property name="useJaf" value="false"/>  
  
  <property name="mediaTypes">  
    <map>  
   <entry key="html" value="text/html" />  
   <entry key="json" value="application/json" />  
   <entry key="xml" value="application/xml" />  
    </map>  
  </property>  
 </bean>  

@RequestMapping(value = "/list.json", method = RequestMethod.GET, produces = { "application/json" })
@ResponseStatus(HttpStatus.OK)
public @ResponseBody
List<Mesure> list() {
return s.list();
}

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

Convert a single object into a JSON string representation on each line

Can you convert the following data into the desired format through stringification? Data: let result = JSON.stringify([ { "Color": "Red", "Type":"Fast" }, { "Color": "Blue&quo ...

Tips for conducting unit tests on navigator.notification.alert

I am currently facing a challenge in writing a unit test for a JavaScript function where I need to fake the navigator.notification.alert method. Can anyone provide suggestions or solutions? Below is the code snippet that I have attempted: navigator = { ...

Error: Please provide the required client_id when setting up Google Sign-In with Next-Auth

I have been trying to implement the Sign in with Google option in my Next.js application using next-auth. Below is a snippet of my [...nextauth].js file located in the api/auth folder: import NextAuth from "next-auth"; import Google ...

Generate a .py file through an HTML button click and save it to your device

My current project involves developing HTML and JavaScript code for a chatbot. I need to implement a feature where, upon receiving a Python program from the chatbot, a download button should be displayed. When users click on this Download button, they shou ...

Utilizing JavaScript to add classes to a parent element

When a user clicks on a link, I want to add a class to the <li> tag that wraps around it. Here is an example: <ul> <li><a href="#">Just an Example</a></li> </ul> How can I target the <li> element enclosing ...

Obtaining numerous data points in a multi-select element within HTML

Struggling with determining the values of multiple <select> tags in an HTML file simultaneously? function knowAllValues(){ var color_element = document.getElementById("color"); var size_element = document.getElementById("size"); ...

Clearing local storage in JavaScript after a certain period of time

On my signup page, I have divided the process into 5 stages and am using the user ID to track which stage they are at by storing it in local storage. However, I would like to automatically remove the ID from local storage if users leave my website without ...

Gson - The issue with my JSON file caused by the loop

My "example.json" file looks like this before I execute my code: { "example1": { "example2": { "example3": 30 } } } After running the following code: JsonManager.writeString("example", "example1", "example2", "example7", "70"); This fun ...

Arranging the Bars in a Bar Chart Using Chart.JS

Lately, I've been playing around with ChartJS and encountering an issue with sorting the bars in descending order, from lowest to highest. Despite my efforts to troubleshoot, I haven't had any success in resolving it. ...

Is JSON required to transmit an object using socket.io?

I have an object on the frontend that I want to broadcast to all connected clients. Can I send it as is, in its original form? Or do I always have to convert it into a JSON string before sending? Here is my object: var myBox = { x: 400, ...

Sending multiple arguments to a Vuex action

In the Vue Component code snippet below, I have a method: loadMaintenances (query = {}) { this.getContractorMaintenances(this.urlWithPage, query).then((response) => { this.lastPage = response.data.meta.last_page }) } I am trying to pass the par ...

What is the reason behind classList returning 'undefined' unless getElementById is explicitly used?

Why is it that I can't seem to select multiple elements with the same class (using querySelector, querySelectorAll, getElementsByClassName, etc) and use classList to check if just one div contains a specific class? I've come across tutorials tha ...

Failure to validate two dates, even when they are both in date format within AngularJS

Although it may seem silly to ask, I am confused as to why this is not working. Even though all the values appear fine in debug mode. My goal is to display an error if the productionStartFrom date is before the current date. Controller scope.currentDate ...

Error encountered while making a REST API call in Ajax: Unforeseen SyntaxError: Colon unexpected

I am currently troubleshooting my code to interact with a REST API. My platform of choice is "EspoCRM" and I aim to utilize its API functionalities. The official documentation recommends using Basic Authentication in this format: "Authorization: Basic " ...

Here's a method for transferring data from one array to another: when there is existing data in the

Although this may seem simple to some, I have been struggling with it for hours without any success. If I have the following data in an array: var tDataValues = { id: "TenantID", text: "FullName", username: "Username", cnic: 'CNIC&ap ...

Encountering a Next.js application error while utilizing the button tag in conjunction with generating metadata

I keep encountering an issue with generateMetaData when trying to utilize the button tag. Can you help me resolve this problem? Currently, I am working with nextjs and I am unable to properly use the <button> tag. Whenever I implement generateMetaD ...

Is a webpage's sluggishness in Internet Explorer due to its lengthy page structure causing issues while loading quickly on other browsers?

My application has a page that is particularly long, around 8Mb of source HTML mainly comprised of tables. I am aware that this indicates poor architecture, but unfortunately, I am unable to make immediate changes due to certain constraints. In most brows ...

Guide to configuring browserify

After installing the modules (browserify, react, reactify), I attempted to process a JSX file using browserify. var React = require("react"); var App = React.createClass({ render: function () { return <h1>111</h1> } }); React ...

Tips for creating multiple full-screen overlays in HTML

I am new to the world of web development and I am currently working on implementing a set of buttons that will trigger specific overlays when clicked. I found the following code snippet on W3schools which creates a button along with an overlay effect. < ...

Utilizing React hooks to capture the checkbox value upon change and transfer it to the submitForm function

I've got a functioning hook that monitors the onChange event of input fields, then spreads them into a variable and sends them to a Lambda function for sending an email with SendGrid. Everything is working fine. However, when I add an input type of c ...