Unable to merge geojson and json data in Leaflet map display

To send information to the map, utilize this code:

function join(){            
    $.when(
        $.getJSON('bairro.json'),
        $.getJSON('convertJson.php')
    ).done(function(responseGeojson, responseData) {
        var data = responseData[0]
        var geojson = responseGeojson[0]

        // Create a hash table for easy reference
        var dataHash = {}
        console.log('==data==');
        console.log(data);
        data.forEach(function(item) {
            if(item.cod) 
            dataHash[item.cod] = item.cod;
            if(item.nome) 
            dataHash[item.nome] = item.nome;
            if(item.local) 
            dataHash[item.local] = item.local;

        })
        // Assign values from hash table to geojson properties
        geojson.features.forEach(function(item) {
            console.log('-->' + dataHash[item.properties.nome]);
            item.properties.Codigo = +dataHash[item.properties.cod]   || null
            item.properties.Nome   = +dataHash[item.properties.nome]  || null
            item.properties.Local  = +dataHash[item.properties.local] || null

        })

    })
}

However, there are issues with undefined values and no image displaying on the map.

Here is an example of how Geojson looks:

{"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "NOME": "local1", "REGIAO_ADM": "value1", "CODBAIRRO": "13"}, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 694555.509827277157456, 7483079.800010865554214 ], [ 694554.849827276892029, 7483077.34010686352849 ], [ 694551.869923274731264, 7483076.470026861876249 ],...}
{ "type": "Feature", "properties": { "NOME": "local2", "REGIAO_ADM": "value2", "CODBAIRRO": "13"}, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 694555.509827277157456, 7483079.800010865554214 ], [ 694554.849827276892029, 7483077.34010686352849 ], [ 694551.869923274731264, 7483076.470026861876249 ],...}
{ "type": "Feature", "properties": { "NOME": "local3", "REGIAO_ADM": "value3", "CODBAIRRO": "13"}, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 694555.509827277157456, 7483079.800010865554214 ], [ 694554.849827276892029, 7483077.34010686352849 ], [ 694551.869923274731264, 7483076.470026861876249 ],...}

This illustrates how the JSON file is structured:

[{ "cod": "13", "local": "local1", "nome": "value1" }, { "cod": "98", "local": "local2", "nome": "value2" }, { "cod": "97", "local": "local3", "nome": "value3" }]

If you have any insight into what might be going wrong or can provide assistance, please let me know!

Answer №1

To expand your array functionality, consider transforming it into a map for easy value lookup based on an identifier (the key). The desired data structure would be:

Original Array:

[{id:"A",property:"value1"},{id:"B",property:"value2"}, .... ]

Transformed Map:

{A:{id:"A",property:"value1"},B:{id:"B",property:"value2"}, .... }

This way, accessing the properties of object A becomes a straightforward task.

Currently, your code lacks the association between keys and values. It assigns property values to create an array with properties having a value equal to the property name:

dataHash[item.cod] = item.cod;

For instance, if item.cod is "foo," then dataHash.foo equals "foo." However, dataHash[item.cod] does not nest properties:

var data = [{cod:1,nome:2,local:3},{cod:4,nome:5,local:6}]
        
var dataHash = {};
data.forEach(function(item) {
    if(item.cod) 
    dataHash[item.cod] = item.cod;
    if(item.nome) 
    dataHash[item.nome] = item.nome;
    if(item.local) 
    dataHash[item.local] = item.local;
})
        
console.log(dataHash);

There are various approaches to achieving your goal. When creating your dictionary for the data, you could use code similar to the following (assuming property names do not start with a number):

var lookup = {};
data.forEach(function(item) {
    if(item.id) {
      lookup[item.id] = {
        id: item.id,
        property1: item.property1,
        property2: item.property2,
        property3: item.property3
      }   
    }
  })

Alternatively, if you want all properties included in the dictionary:

var lookup = {};
data.forEach(function(item) {
    if(item.id) {
      lookup[item.id] = item
    }
  })

This assumes no duplicate entries exist in your data.

var data = [
 {id:"id1",property1:"text1",property2:"text2",property3:"text3"}, 
 {id:"id2",property1:"textA",property2:"textB",property3:"textC"}];
       
var lookup = {};
data.forEach(function(item) {
    if(item.id) {
      lookup[item.id] = {
        id: item.id,
        property1: item.property1,
        property2: item.property2,
        property3: item.property3
      }            
    }
})

console.log(lookup)

You can now easily look up the values to join each element in the geojson:

geojson.features.forEach(function(item) {
    if(lookup([item.properties.id])) {
        item.properties.joined = lookup[item.properties.id]
    }
})

Since the geojson may have properties with the same name as the incoming data, we group all joined properties under a subproperty named joined.

For your specific data, the entire operation might look like this:

var geojson = {"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "NOME": "local1", "REGIAO_ADM": "value1", "CODBAIRRO": "13"}},
{ "type": "Feature", "properties": { "NOME": "local2", "REGIAO_ADM": "value2", "CODBAIRRO": "13"}},
{ "type": "Feature", "properties": { "NOME": "local3", "REGIAO_ADM": "value3", "CODBAIRRO": "13"}}
  ]}
  
var data = [{ "cod": "13", "local": "local1", "nome": "value1" }, { "cod": "98", "local": "local2", "nome": "value2" }, { "cod": "97", "local": "local3", "nome": "value3" }]


var lookup = {};
data.forEach(function(item) {
if(item.local) {
    lookup[item.local] = item;            
}
})

geojson.features.forEach(function(d) {
if (lookup[d.properties.NOME]) {
    d.properties.joined = lookup[d.properties.NOME];
}
})

console.log(geojson);

The code snippet assumes that local (in the json) and NOME in the geojson are unique values used for the join process.

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

jQuery - final slide not triggering interval, causing animation malfunction

I am working on creating a slider using multiple divs instead of images. I have a total of 3 divs, and while the first two transition smoothly as intended, the third div seems to fly away too quickly - it briefly appears and then snaps back to the first di ...

Transferring data between Django and JavaScript: dealing with DateTime information

I'm facing an issue while attempting to transfer data (step_count_data) from Django to a JavaScript function. Below is the code snippet: Django #somecode step_count_date.append(str(step_count_list[i].startTime.date())) context = {'step ...

Is it necessary to generate a file for each API in Next.js?

When working with Next.js, it is common practice to create a separate file for each new API endpoint. For example, for the /user endpoint, there would be a user.js file with its own handler, and another one for /user/goldmember. Some may argue that this ...

Create an animated A-frame box that moves randomly within a designated space

Looking to add some movement to my A-frame scene with a random box animation. I want to utilize the animation property to make an entity move randomly within a specified area. The goal is to have a box animate to a random position within coordinates rang ...

Exploring the depths of nested objects within HTML for Angular programming

I am currently working with a data structure that is defined as follows: app_list = ["app_1", "app_2"] data["results"] = { "app_1": [ {"key":1}, {"key":2} ], "app_ ...

The element type provided is not valid: it is expected to be a string (for built-in components) or a class/function (for composite components) but instead it is undefined. This error

I am encountering an error of Element type is invalid: expected a string (for built-in components) or a class/function (for composite components). It seems like I may have forgotten to export my component from the file it was defined in, or there could be ...

Filling an HTML modal with either keys or values from a JSON array

I'm facing a simple issue that I can't seem to solve. What am I missing here? I receive a PHP array through JSON encoding: var curr_op = <?php echo json_encode($options) ?>; When I console.log(curr_op), it shows: [14:35:00.889] ({' ...

Error in JSON Deserialization

I need to send the json data to the server, and below is the format of the json: [{"StaffID":"S01","StaffRank":"Manager"},{"StaffID":"S02","StaffRank":"Waiter"}] When I attempted to retrieve the json array using the following code: Dim request As Stri ...

The error message "TypeError: scanner.js is undefined and property 'scan' cannot be read" is occurring

I've been attempting to incorporate scanner-js into my react application, but I keep encountering the error TypeError: Cannot read property 'scan' of undefined. The code snippet is provided below: import { scanner } from 'scanner-js&ap ...

Tips for accessing the JSON file containing Spark driver metrics:

After following the monitoring guide at , I tried configuring the metricsservlet but found the documentation to be lacking in useful information. According to the commons in metrics.properties: "5. MetricsServlet is added by default as a sink in master, ...

Can the swap operation be carried out using web3.js and a forked HardHat implementation?

Embarking on my journey into ethereum development, I am currently engrossed in crafting a basic script that facilitates swaps using web3.js. To begin with, my web3 is establishing a connection to the HardHat forked server. The first step involves setting ...

Integrating Livefyre npm with Meteor

Currently, I am in the process of creating a custom package to integrate the livefyre npm module into Meteor after receiving a request from a client. Despite following the instructions provided here, I keep encountering errors that state Errors while scann ...

Creating a custom JavaScript library using an existing npm module (codius)

Embarking on a new journey with this, never tried it before. Currently utilizing https://github.com/codius/codius-host. The development of Codiu§ has been abandoned, however I am determined to salvage some parts of it for my own project. It is crucial fo ...

Pass the output of canvas.toDataURL function in JavaScript to the $mail->addAttachment method in PHP

Currently, I am working on a web application that allows users to customize a pool by dragging different icons onto a blueprint (such as stairs, skimmer, light...). Once the customization is complete, users can click on a button to receive the blueprint v ...

Find the most affordable rate in the JSON data without knowledge of the parent label

I am seeking to extract the best deal from JSON data obtained through an API call and decoded using json_decode. The structure is as follows: products productnumber -> price $product_array['products'][..changingnumber..]['value'] ...

Using function arguments as private variables in JavaScript allows for better encapsulation

Have you ever wondered if function arguments automatically become private variables within the function? I came across this interesting concept and decided to experiment: var node = function(nParent,nName,nContent){ this.init = function(){ ale ...

Display pop-up notification box in Yii2 when receiving an AJAX request

I am currently working with this jquery code in one of my view files $('#ticket-ticket_impact_id').change(function() { var priority = $('#ticket-ticket_priority_id :selected').val(); var impact = $('#ticket-ticket_impact_id : ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...

strange python dictionary update operation

This morning, I encountered a strange issue: >>> list = ['a', 'b', 'c'] >>> dictionary = dict.fromkeys(list, []) >>> dictionary['a'] += [1] >>> dictionary {'a': [1], & ...

Vue: Issue with v-for rendering images as strings

How can I display the actual image of the user in my table instead of just the image name as a string when using v-for? In Laravel Blade, I can easily achieve this by using a foreach loop. Any suggestions on how to accomplish this in VueJS? Thanks! Here i ...