picking out a particular set of data from a JSON document

I have a map of Europe along with a JSON file that displays the unemployment rate for each country in the year 2011. The JSON file also includes x and y elements, allowing me to place a blue circle on top of each country on the map.

My goal is to be able to hover over one of these circles (representing a country) and retrieve and display its unemployment rate from the JSON file.

How can I extract the 'rate' element specific to the country I'm hovering over on the map from my JSON file?

JSON FILE:

[
{ "year": "2011", "country": "Finland", "rate": 8.0, "x":681, "y":18 },
{ "year": "2011", "country": "Sweden", "rate": 7.6, "x":486, "y":114 },
{ "year": "2011", "country": "Estonia", "rate": 13.6, "x":625, "y":206 },
...

jQuery File

$(document).ready(function(){
$.getJSON("eu.json", function(data) {
console.log("Data loaded successfully");
$.each(data, function(i, elem) {
        $('<div></div>').addClass('dataPt').css({
            "margin-left": elem.x + "px",
            "margin-top": elem.y + "px",
            "border-width": elem.rate + 5 + "px"
        }).appendTo('#map');
        $('div.dataPt').hover(function(){
    $(this).addClass("dataPtHover");

},function(){
    $(this).removeClass("dataPtHover");
}); 
});
});
});

Check out this jsfiddle link to better understand what I am trying to achieve.

http://jsfiddle.net/RSEyg/

Answer №1

To simplify the process, consider utilizing jQuery data as demonstrated below: (updated example here: http://jsfiddle.net/RSEyg/4/)

$(document).ready(function(){
  $.each(data, function(i, elem) {
            $('<div></div>').addClass('dataPt').css({
                "margin-left": elem.x + "px",
                "margin-top": elem.y + "px",
                "border-width": elem.rate + 5 + "px"
            }).appendTo('#map').data("rate", elem.rate);

    });

   $('div.dataPt').hover(function(){
        $(this).toggleClass("dataPtHover");
        $("#unResult").text($(this).data("rate"))        

    },function(){
        $(this).toggleClass("dataPtHover");
    }); 


});

If you require access to additional properties of each country for every pinpoint, store the complete object in data and retrieve the necessary attributes when needed.

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 is preventing me from assigning all padding values at once?

I attempted to modify all paddings of the html element using JavaScript, with the following code: const pd = 1 document.getElementsByClassName('board')[0].style.paddingRight = pd + 'px' document.getElementsByClassName('board') ...

What is the best way to fix character encoding issues with native JSON in Internet Explorer 8

When working with JSON containing Unicode text, I encountered an issue with the IE8 native json implementation. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script> var stringified = JSON.stringify("สวัส ...

Organizing DIVs upon website initialization

My website features a layout with three columns: <div id="column1"></div> <div id="column2"></div> <div id="column3"></div> I currently have 3 divs on the webpage: <div id="1">aaa</div> <div id="2">b ...

Which comes first in AngularJS: ng-include or ng-repeat?

What is the outcome if I have a template containing ng-repeat and include it using ng-include? Will the included template have the completed ng-repeat, or will it be included without the ng-repeat being complete (and then completed after inclusion)? ...

Encountering an Issue Retrieving User Orders - Receiving 401 (Unauthorized) Status Code

I am currently working on a React project focused on displaying user orders. I have successfully integrated JSON Web Tokens (JWT) for user authentication. However, I keep encountering a persistent 401 (Unauthorized) error when trying to retrieve the user&a ...

Implementing PHP logic for adding a class to an HTML tag

I have a PHP file that handles the sending of my form. Everything is functioning correctly, but I need to make a small modification. When the message is successfully sent, I want PHP to dynamically add the "active" class to a specific div in my HTML. This ...

Decoding JSON data using Gson

Here is some JSON data I am working with: { "boards": [ { "board": "3", "title": "3DCG", "ws_board": 1, "per_page": 15, "pages": 11 }, { "board": "a", "title": "Anime & Manga", ...

Saving the current date and time in PHP and JS to persist even after the browser has been closed

I am currently facing a situation where I can click on an image and it will display a new image. In the previous grid-item, it shows the day and time I clicked on it. What I want to achieve is to have this functionality persist even after closing and reop ...

Adjusting the gap between TableRows in Material-UI

Is there a way to increase the spacing between TableRow MaterialUI components in my code? <S.MainTable> <TableBody> {rows.map(row => { return ( <S.StyledTableRow key={row.id}> <TableCell component="th" s ...

Mastering the correct application of flex properties within nested flex containers

I'm struggling with utilizing flexbox properly and would like some clarification on how nesting parent and child elements functions. I understand that the child elements inherit the parent's flex properties, but I'm unsure if this inheritan ...

Tips for inputting information without redundancy after selecting a specific designation

I'm experiencing a challenge with this code as it repeats when already chosen. My goal is to add data in the database once something has been selected. When I click on spin, the randomizer will choose a name and update their status to "done". Subsequ ...

What is the implication when Typescript indicates that there is no overlap between the types 'a' and 'b'?

let choice = Math.random() < 0.5 ? "a" : "b"; if (choice !== "a") { // ... } else if (choice === "b") { This situation will always be false because the values 'a' and 'b' are completely disti ...

Resolving the dilemma of complete form validation in Jquery

I'm currently working on a PHP form that is being validated with jQuery. In this form, there is a radio button list. If the user clicks "Yes," then the textbox related to that radio button should not be validated. However, if the user clicks "No," the ...

Retrieving array values from various fields with identical CLASS using jQuery and utilizing AJAX to transmit the information to PHP

I need to extract values from multiple fields with the same CLASS using JavaScript and then utilize AJAX to send the data to PHP <input type="text" class="form-control subject" placeholder="Subject name"> <input t ...

Retrieve the Id value from a Kendo Hierarchical grid

I have a hierarchical grid set up with a ClientDetailTemplate in the following manner. @(Html.Kendo().Grid(Model.NotesList) //Binding the grid to NotesList .Name("activityNotesGrid") .Columns(columns => { // Creating a col ...

In your experience, what's the most efficient method you've come across for editing tags?

Currently, I am working on implementing a feature that allows users to edit the list of tags displayed next to each link on a website. This includes adding, removing, and modifying tags. I am searching for an efficient way to make this process user-friend ...

Tips for hiding text on hover effect

I'm currently working on a menu where each item displays text that is replaced by an email address on hover. However, I am struggling to remove the text during the hover state. Below is the code I have written so far: #home { font: 30px 'Le ...

Use Vue JS to send a GET request to the server with custom header settings

When creating a Vue.js component, I want to send a GET request to a server with specific headers. How can I achieve this? Using cURL: -X GET "http://134.140.154.121:7075/rest/api/Time" -H "accept: application/json" -H "Authorization: Bearer eyJhbGciOiJSUz ...

Tips for centering a video vertically within a cell

I need assistance with aligning a video in the center of a fixed height cell while hiding the overflow at the top and bottom. Here is what I have so far: <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td height ...

Learn how to showcase a predetermined option in an HTML select element using Vue.js and Minimalect

I am currently utilizing Vue.js along with the Mininmalect HTML select plugin to showcase a list of countries by their names and values, where the value represents the 2 digit country code. Successfully, I have managed to implement the plugin for selectin ...