Using Leaflet to beautify categorical json information

As a beginner in coding, I must apologize if a similar question has already been asked. I've spent days searching but haven't found the right combination of terms to find examples for my scenario.

I am exploring various small use cases of different web-mapping services to create color-coded maps of parcels based on land use. Specifically, I am working with Leaflet to map parcel data stored as a JSON object named downtownParcels_all.json. This file contains geometry and attributes for each parcel like this:

{ "type": "FeatureCollection", 
"features": [ { 
    "geometry": 
        { 
            "type": "Polygon", 
            "coordinates": 
                [ 
                    [ 
                        [ -84.55903531544767, 38.20711817093237 ], 
                        [ -84.55905917105294, 38.20683120640012 ], 
                        [ -84.55925392867115, 38.20684358736447 ], 
                        [ -84.55922953052168, 38.2071413284724 ], 
                        [ -84.55903531544767, 38.20711817093237 ] 
                    ] 
                ] 
        }, 
"type": "Feature", "properties": 
    { 
        "Complete_A": "121 E JACKSON ST", 
        "MailAddres": "121 E JACKSON STREET", 
        "ParcelID": "123-45-6", 
        "GIS_MapID": "123-45-678.000", 
        "Acres": 0.13, 
        "Name2": null, 
        "MailAddr_1": "GEORGETOWN KY 40324", 
        "Name1": "SMITH JOHN", 
        "LandUse": "11-1 Single Family" } 
},

...etc...

I intend to color the parcel polygons based on properties.LandUse. Using this example as a guide, I encountered issues adapting the styling function from quantitative to qualitative data. The parcels appear without conditional styling despite not receiving an error message.

Below is my code attempting to style parcel polygons based on the Land Use data stored within a JSON object. Please note that I have kept the term "state" in variable names for reference back to the inspiration example:

var map = null;
var state_layer = null;
var states_geo_json = null;
var states_data = null;

// Loads data, initializes map, draws everything.
function start(){
  $.getJSON("data/downtownParcels_all.json",function(us_states){
    states_geo_json= us_states;
    initialize_map();
    draw_states();
  });
}
start();

/* Create map, center it */
function initialize_map(){
  map = new L.Map("map", {})
    // Lebanon, KS, Zoom level 4.
    .setView(new L.LatLng(38.212, -84.556), 15)
    .addLayer(new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }));
}

// Draw all the states on the map
function draw_states(){
  state_layer = L.geoJson(states_geo_json,{
    style: state_styles,
    //onEachFeature: state_features,
    updateWhenIdle: true
  });
  state_layer.addTo(map);
}

// Styles each state, populates color based on data
function state_styles(feature){
  return{
    stroke: true,
    fillColor: state_color,
    fillOpacity: 0.7,
    weight: 1.5,
    opacity: 1,
    color: 'black',
    zIndex: 15
  };
}

function state_color() {
  for (var i = 0; i < us_states.length; i++) {
    var landUse = us_states[i].properties.LandUse;
    switch(landUse) {
      case "11-1 Single Family": return "#ffffb2";
      case "11-2 Multi-Family": return "#fed976";
      case "11-3 Apartments": return "#993404";
      case "12-1 Commercial retail": return "#b30000";
      case "12-2 Commercial wholesale": return "#fe9929";
      case "12-3 Services": return "#e34a33";
      case "12-5 Government": return "#f768a1";
      case "12-6 Institutional": return "#045a8d";
      case "12-7 Educational": return "#a6bddb";
      case "16-1 Mixed use": return "#810f7c";
      case "21-1 Agricultural": return "#31a354";
      case "99-1 Vacant": return "#f7f7f7";
      case "99-4 Parking": return "#636363";
    }
  }
}

If you have any suggestions on improving my current code or can help me achieve categorical symbolization more efficiently, I would greatly appreciate it. I'm happy to clarify anything if needed. Thank you!

Answer №1

In reviewing the code, it appears that there is a line where fillColor is set to state_color.

fillColor: state_color,

To accurately represent this relationship, it should be changed to:

fillColor: state_color(feature),

This adjustment clarifies that fillColor corresponds to the color returned by the state_color function for a specific feature.

Furthermore, in the state_color function, an argument should be incorporated as follows:

function state_color(layer) {

Additionally, given that the state_color function only operates on one feature at a time, the for loop within should be removed. As for the line

var landUse = us_states[i].properties.LandUse;
, it would be more appropriate to reference layer.feature.properties.LandUse.

These adjustments should provide a solid foundation moving forward.

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

How to retrieve the data variable in Vue JS script

I recently started using vue.js and I'm working with version 2.5.13. In my component file script, I am trying to access a data variable but it keeps returning as undefined. The id attribute in the component is displaying the correct value, however w ...

Utilizing AJAX to dynamically update a div on a separate webpage

In my application, I have a page called news.jsp that displays a list of news titles. Users can click on a title to read the full body of the news, which is loaded using AJAX within a span tag on the same page. Additionally, I display the top 5 news storie ...

How can I use variables to show the second dropdown list only when a value has been selected in the first dropdown?

Is there any way I can choose a specific value from a dropdown list and based on that selection, show another dropdown list? I understand how to do it with regular words, but what if I use variable names? University Name: <select name="university" id=" ...

Obtain the ID of element 1 by clicking on element 2 using JQuery

In the world of javascript/jquery, When button1 is clicked, we can get its id like this: var button1id = $(this).attr("id"); If button2 is clicked, how do we retrieve button1's id? This brings us to the question: How does button2 access the i ...

Scrolling and hovering now triggers the fixed button to toggle class seamlessly

Currently, I am attempting to modify the class of a button on my website. The initial state of the button is wide, but as the user scrolls, it should shrink in size. When hovering over the shrunken button, it should expand back to its original width. Alt ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

JavaScript game with server-side communication and answer validation functionality

In my fast-paced, quiz-like Javascript game, users must answer a series of Yes/No questions as quickly as possible. Upon answering, the response is sent to the server for validation and feedback (correct/incorrect) before moving on to the next question usi ...

What is the best way to share models across different node.js projects?

In my setup, I have two node.js projects - project A and project B. Project A serves as the main project, while project B is more of an "ad-hoc" project with a specific purpose. The challenge lies in the fact that project B requires access to project A&apo ...

I am looking to sort through the data based on the courseCode, but I can't seem to find a way to do it

Here is the JSON data after converting it with res.json() I attempted to filter it based on course code, let's say the code is: 301. I am confused about how to achieve this using JavaScript because of the nested structure. Here is the code snippet I ...

The database is failing to reflect any changes even after using the db.insert function

I am currently working on implementing a forgot password feature in my express app using the node mailer package. This functionality involves sending a new password to the user's email and then updating the database with the new password. However, I h ...

What is the process for obtaining a JSON structure that represents a Mongoose schema?

Currently, I am working on creating an API in Express and utilizing Mongoose for my data layer. My goal is to make the API as self-explanatory as possible so that the frontend can automatically create forms and validations based on the schema rules establi ...

Using HTML5 chunks and web workers will not involve any uploading of files

I encountered an issue while working with html5 slice and webworker. It seems that when I try to upload a file using the uploadFile function, nothing is happening and the file is not being uploaded. <html> <head> <title>Uploa ...

Change a list into JSON format with Jackson library

After running the code mentioned below, I successfully converted a list to JSON with the following format: {"GodownMaster":[{"pname":"FCI CHARLAPALLI","pcode":"16042"}, {"pname":"MLS CIRCLE 1 L.B. NAGAR","pcode":"16016"},{"pname":"MLS CIRCLE 4 AZAMABAD", ...

Refresh the page only when on the initial page of the pagination

I've been utilizing this jQuery code with AJAX for pagination purposes. Currently, I am fetching data from a PHP file that displays limited information. Here is the index file snippet: <script type="text/javascript"> $(document).ready(fun ...

The thumbnail image is failing to load, and when I hover over an image, it moves upwards

I seem to be encountering an issue with a website I uploaded for testing. Everything appears to be working correctly when checked locally in Dreamweaver CS6. However, once the site is uploaded, some issues arise. When hovering over the images, a problem is ...

A guide on managing multiple onClick events within a single React component

Including two custom popups with OK and Cancel buttons. Upon clicking the OK button, a review is composed. This review code is then sent to the server via a post request. Subsequently, the confirmation button reappears along with a popup notifying the user ...

Navigating to the next or previous item in an Angular2 Firebase collection based on the current key

In my photo gallery, I have the key of an item in firebase and would like to enable users to navigate to the next or previous picture by pressing buttons. In a non-Angular2 context, I might use the following code snippet to retrieve the next item: ref.ord ...

Understanding ElectronJs: Decoding the significance of curly braces '{}' within the package.json file

As I was reviewing some electron package.json examples, I came across certain interpolations as shown below: "updater": { "urls": { "darwin": "{{& SQUIRREL_UPDATES_URL }}/update/%CHANNEL%/darwin?version=%CURRENT_VERSION%", "win32": "{{ ...

Issue with triggering a modal while simultaneously closing another one

Let's consider this situation. I currently have a modal called Modal A, which has 2 buttons in the footer: Save and Close. When I click on the "Save" button, my intention is to close Modal A and open Modal B. The code that achieves this functionality ...

Error while retrieving reference from mongoDB in NodeJS

I am currently working on a small website that needs to query my local mongodb. Everything works perfectly fine on localhost. That's why I decided to begin with NodeJS. While all JavaScript functions work seamlessly when run separately, I encounter a ...