Utilizing JSON to define conditions in OpenLayers vector layers

How can I extract specific information from a JSON file using openlayers.vector based on certain conditions? For example, if the "type" is equal to "etat5", I want to retrieve the URL and name.

    var geojson_etat7 = new OpenLayers.Layer.Vector("etat7", {
        styleMap: new OpenLayers.StyleMap({
                    "default": new OpenLayers.Style({
                    externalGraphic: './images/Etat${url}.png', 
                    graphicWidth: 21, 
                    graphicHeight: 25,
                    graphicYOffset: -24,
    ===>>>>>>               label : "name: ${name}"

                    } ),

                }),
        projection: epsg4326,
        strategies: [new OpenLayers.Strategy.Fixed()],
        protocol: new OpenLayers.Protocol.HTTP({
            url: "data/data_etat5.geojson",
            format: new OpenLayers.Format.GeoJSON()
            })

        });

This snippet represents my JSON database:

{
"type": "FeatureCollection",
"features": [
{
  "type": "etat5",
  "properties": {
        "name": "test",
        "amenity": "toto",
        "popupContent": "popo",
        "url":"5"
    },
  "geometry": {
    "type": "Point",
    "coordinates": [
      26.9140625,
      26.9449741808516
    ]
  }
},
{
  "type": "etat5",
  "properties": {
          "name": "tt",
          "url":"5"
  },
  "geometry": {
    "type": "Point",
    "coordinates": [
     53.15008544921875,
      21.3425828520359735
    ]
  }
},
{
  "type": "etat1",
  "properties": {
        "name": "test",
        "amenity": "toto",
        "popupContent": "popo",
        "url":"1"

    },
  "geometry": {
    "type": "Point",
    "coordinates": [
      38.9140625,
      56.9449741808516
    ]
  }
},
   {
  "type": "etat1",
  "properties": {"url":"1"},
  "geometry": {
    "type": "Point",
    "coordinates": [
      -2.15008544921875,
      1.3425828520359735
    ]
  }
},
{
  "type": "etat2",
  "properties": {
        "name": "test",
        "amenity": "toto",
        "popupContent": "popo",
        "url":"2"

    },
  "geometry": {
    "type": "Point",
    "coordinates": [
      26.9140625,
      46.9449741808516
    ]
  }
},
   {
  "type": "etat2",
  "properties": {"url":"2"},
  "geometry": {
    "type": "Point",
    "coordinates": [
     3.15008544921875,
      11.3425828520359735
    ]
  }
},
{
  "type": "etat3",
  "properties": {
        "name": "test",
        "amenity": "toto",
        "popupContent": "popo",
        "url":"3"
    },
  "geometry": {
    "type": "Point",
    "coordinates": [
      16.9140625,
      26.9449741808516
    ]
  }
},
   {
  "type": "etat3",
  "properties": {"url":"3"},
  "geometry": {
    "type": "Point",
    "coordinates": [
     23.15008544921875,
      31.3425828520359735
    ]
  }
},
  {
  "type": "etat4",
  "properties": {
        "name": "test",
        "amenity": "toto",
        "popupContent": "popo",
        "url":"4"
    },
  "geometry": {
    "type": "Point",
    "coordinates": [
      3.9140625,
      16.9449741808516
    ]
  }
},
   {
  "type": "etat4",
  "properties": {"url":"4"},
  "geometry": {
    "type": "Point",
    "coordinates": [
     23.15008544921875,
      71.3425828520359735
    ]
  }
},
{
  "type": "etat6",
  "properties": {
        "name": "test",
        "amenity": "toto",
        "popupContent": "popo",
        "url":"6"
    },
  "geometry": {
    "type": "Point",
    "coordinates": [
      16.9140625,
      36.9449741808516
    ]
  }
},
   {
  "type": "etat6",
  "properties": {"url":"6"},
  "geometry": {
    "type": "Point",
    "coordinates": [
     43.15008544921875,
      111.3425828520359735
    ]
    }
   }
 ]
}

Answer №1

The GeoJSON parser relies on the type attribute to distinguish between Geometry, Feature, and FeatureCollection. Changing this structure could cause issues with parsing. For properties, they are parsed and become attributes of the Feature Vectors returned by GeoJSON.read function.

var reader = new OpenLayers.Format.GeoJSON();
var features = reader.read(json);
for (var i = 0; i < features.length; i++){
    if(features[i].attributes['type'] === 'etat5'){
        console.log(features[i].attributes['url']);
    }
};

An example JSON structure is shown below:

var json = {
  "type": "FeatureCollection",
  "features": [{  
     "properties": {
        "type": "etat5",
        "name": "test",
        "amenity": "toto",
        "popupContent": "popo",
        "url": "5"
    },
     "geometry": {
       "type": "Point",
       "coordinates": [
       26.9140625,
       26.9449741808516
     ]
    } 
  }
]};

Answer №2

let geojson_state7 = new OpenLayers.Layer.Vector("state7", { styleMap: new OpenLayers.StyleMap({

                    "default": new OpenLayers.Style({
                    externalGraphic: './images/State${name}.png', 
                    graphicWidth: 21, 
                    graphicHeight: 25,
                    graphicYOffset: -24,
                    label : "${total}"
                    },
                    { context: {
                        total: function(feature){
                            var tt=" state7";
                            //return tt;
                            if(feature.attributes.url=="4"){
                            return  tt;
                            }


                        },
                        name: function(feature){
                            var tt="4";
                            //return tt;
                            if(feature.attributes.url=="4"){
                            return  tt;
                            }


                        }
                    }
                    } )  

                }),
        projection: epsg4326,
        strategies: [new OpenLayers.Strategy.Fixed()],
        protocol: new OpenLayers.Protocol.HTTP({
            url: "data/data_state5.geojson",
            format: new OpenLayers.Format.GeoJSON()
            })

        });

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

What reasons could explain why the more efficient approach of offering an initial portion of data is not faster in practice?

My website contains numerous pages with a plethora of small images that need to be loaded. To enhance user experience, I devised two methods to first display a subset of the content without waiting for the entire page to load. The data is stored in a .json ...

Promise.all does not pause for a new Promise to finish resolving

This particular section belongs to a spa utilizing nodejs and jquery. The getToday function is supposed to console log "result:", leading to the entire output being 1, followed by result:, and finally 2. However, it seems that the code does not wait for ge ...

Redirecting to new page after submitting form using Ajax

I'm having some trouble with my HTML form submission using JQuery and AJAX. After successfully submitting the form, I want to display a modal and then redirect to another page based on certain conditions. I've written the logic in my JS file wh ...

Utilizing Python for Retrieving JSON Data

I have a script that is currently reading a JSON file and I need to format the output in a specific way. The current output in firebase appears like this: Value: 0: "{'status': 'success'" 1: " 'country': 'Malaysia&apo ...

npm is having trouble locating the module called 'encoding'

I've run into a npm issue on my newly formatted Ubuntu OS laptop while using VSCode. The error I encountered during installation is: npm ERR! code MODULE_NOT_FOUND npm ERR! cannot find module 'encoding' // Log 0 info it worked if it e ...

populating information to compress using Javascript

I am facing an issue with my button. I want to be able to click on it and have the data populate in the collapse using JavaScript, but for some reason it is not working. The collapse functionality is working fine when I click the button, so there is no pr ...

Manipulating text field value in Javascript and PHP

I'm currently working with a script that retrieves 2 values from my database. $(document).ready(function() { <? $link=new mysqli($serveur,$login,$pass,$base); mysqli_set_charset($link, "utf8"); $r=mysqli_query($link, "select sujet ...

No tests were located for execution. Despite our efforts, a cypress.json file was not found in the search

Having recently set up Cypress in my project, I encountered an issue while attempting to run it using npx cypress run. The error message displayed was: Could not find any tests to run. We searched for a cypress.json file in this directory but did not ...

Encountered an issue when attempting to retrieve an array of objects using axios

I have been encountering an error every time I try to make a get request with axios, while passing an array of hardcoded objects. The error message looks like this: https://i.sstatic.net/XsEle.png I am seeking assistance as I am new to react js. I believ ...

Filter JSON items by attribute based on the most recent date in Ruby/Rails

I am working with a JSON object that looks like this [{"id":"ad-34","date":"28.07.2016","value":"cheese"}, {"id":"ad-34","date":"31.07.2016","value":"cheese updated"}, {"id":"ad-21","date":"31.07.2016","value":"sausage updated"}, {"id":"ad-34","date":"02. ...

How come CSS styles are not being applied to forms in AngularJS?

When attempting to apply CSS styles to a form in order to indicate invalid input, I encountered an issue. Even after using the important tag, the styles did not change. I created a dynamic form from JSON and now need to validate it. Following a suggestion ...

Performing ad-hoc queries on a Postgresql database using Node.js and Express to manipulate row data

I am faced with a challenge of selecting one entry randomly from a table containing 46 entries, and then passing the data from that particular query to my handlebars files. I am unsure about how to approach the task of randomly querying the database and re ...

Updating an Image Using JavaScript

Having trouble changing an image using JavaScript. Followed instructions to use document.getElementbyId("image").src = "image2.jpg", but it's not working. Script is placed at the bottom after the image tag in the HTML. HTML code: ...

Modifying dynamic input fields based on the selected input field type

Seeking advice on a challenge I'm facing while testing a website. My task is to mask input fields in screenshots after executing tests because we share data with other teams. I've tried using JS before the script by changing the input type to &ap ...

Forces of Attraction and Repulsion in Three.js/Physijs: Exploring the Dynamics of Object

For my chemistry extra credit project, I am working on creating a 3D simulation that focuses on the atomic structure of compounds. My goal is to develop a visual representation of elements surrounding a central atom, such as fluorine surrounding nitrogen i ...

Best practices for remotely monitoring and managing a server in real-time using HTTP

Looking to view server CPU, RAM, and HDD stats along with gathering info from various logs on my client device (a phone with a browser). Implementing ajax polling. Every 5 seconds, setInterval is used on the client to call a PHP file: Scan a folder c ...

Issue with React and Material UI: The Textfield's "onChange" event is not being triggered

I have been attempting to trigger an onchange function when my Textfield is populated, but for some reason the function never seems to be activated. Despite seeing changes triggered by the React devtool plugin in Chrome, I am at a loss. Any suggestions? i ...

Avoid using the AJAX function if an identical request is already in progress

I have set up an AJAX request within a JavaScript function. By using the setInterval method, this AJAX function runs every 5000 milliseconds. I am curious if there is a way to determine if the previous AJAX call is still in progress to prevent multiple si ...

Having difficulty maintaining trailing zeroes in decimals after converting to float in Angular

I need assistance with converting a string to float in Angular. Whenever I use parseFloat, it seems to remove the zeros from the decimal values. How can I ensure that these zeros are retained with the numerical values? The example below should provide more ...

Is it possible to convert uncontrolled components from class-based to functional components?

I'm having difficulties converting the Uncontrolled Components from class Components into Functional Components... Class Components: import React from 'react'; class NameForm extends React.Component { constructor(props) { super(props ...