Is there a way to utilize a different API to apply color to GeoJson polygons?

I have a geographical JSON map file containing province IDs and coordinates. Additionally, I am utilizing another API that provides the color associated with each province ID. My goal is to dynamically set the fillColor of each polygon based on the color provided by the API.

Here is a snippet of my GeoJSON file with the first polygon as an example:

 [
        {
          "type" : "FeatureCollection",
          "features" : [
            {
              "type" : "Feature",
              "id" : 0,
              "regionColor": "orangeColor",
              "geometry" : {
                "type" : "Polygon",
                "coordinates" : [...]
              },
              "properties" : {
                "FID" : 0,
                "FID_1" : 0
              }
        }
    ]

My API data (imported as mockData):

{
    "colors": [
        {
            "id": "0",
            "countryColor": "red"
        },
        {
            "id": "1",
            "countryColor": "orange"
        },
        {
            "id": "2",
            "countryColor": "yellow"
        }
    ]
}

Snippet of my code:

<template>
  <div class="container">
    <div id="mapContainer">      
    </div>
  </div>

</template>
<script> 
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import geojson from "../components/provinces.json"
import mockData from "./test.json"

export default{
  name: "locationMap",
  data() {
    return{
      center: [32.87255939010237, 53.781741816799745],
    }
  },

methods: {

setupLeafletMap: function () {
  const mapDiv = L.map("mapContainer").setView(this.center, 5);
  L.tileLayer(
    'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    {
      attribution: '&copy; <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a> contributors',
      // maxZoom: 18,
    }
  ).addTo(mapDiv);

      var myStyle = {
        "fillColor": "#818181",
        "color": "black",
        "weight": 2,
        "opacity": 0.65,
        "fillOpacity": 0.6
      };

    L.geoJSON(geojson,{
     style: myStyle,
    }
   }
  }
mounted() {
    this.setupLeafletMap()
    console.log(mockData.colors[1].id)
  },
}

</script>

Answer №1

You can utilize the L.geoJSON function along with a style function to dynamically apply styles to each feature. By mapping the feature ID to colors in your dataset, you can create a custom style for each feature.

When using L.geoJSON(geoJSONData, {
  style: function (feature) {
    const fid = feature.properties.FID,
          color = mockData.colors.find((color) => parseInt(color.id) === fid);

    console.debug(`Feature with id ${fid} now has color ${color.countryColor}`);

    return {
      fillColor: color.countryColor,
      color: "black",
      weight: 2,
      opacity: 0.65,
      fillOpacity: 0.6
    };
  }
}).addTo(map);

To see a practical example with sample data, you can view this link: https://codepen.io/strfx/pen/XWYNrBM

I hope this information is useful for you!

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

Show the word "Delivered" on the submission button once the message has been sent successfully

Is it possible to customize the "Submit" button text on Contact Form 7 in WordPress? I would like it to change to "Sent" once the user has submitted the form, providing them with feedback that the message has been successfully sent. Thank you for your he ...

Listening to changes in a URL using JQuery

Is there a way to detect when the browser URL has been modified? I am facing the following situation: On my webpage, I have an iframe that changes its content and updates the browser's URL through JavaScript when a user interacts with it. However, no ...

A dialog box resembling a tooltip

Are there any jQuery plugins available that mimic the functionality of the tooltip dialog in the Flow App? (See screenshot here: ). I am currently working on a web app that requires a lot of tooltip dialogs. If there isn't a plugin available, could s ...

Extract items from javascript array based on their index value

Recently I came across a javascript array var countries = ["India","USA","China","Canada","China"]; My goal is to eliminate "China" only from the 2nd position while keeping the rest intact. var countries = ["India","USA","Canada","China"]; I am see ...

Utilizing Bootstrap Modals to seamlessly redirect me to a new empty page

Despite the fact that my website functions perfectly fine without a build system, I am encountering an issue with the Bootstrap modals while using the Yeoman: Angular + Gulp build system. Whenever I click on a list item, instead of the modal appearing, it ...

Best practices for organizing an array of objects in JavaScript

I have an array of objects with nested arrays inside, and I need to restructure it according to my API requirements. [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ w ...

Reset form fields after submission using vuex

I am having trouble clearing a form after submitting it to create a new user. I am using Vuex to reset the state, but for some reason, the form still retains the data. This is what the form looks like: <form @submit.prevent="onSubmit" v-if=&q ...

Why does the type checking for props in vue.js keep failing despite my use of "Object as PropType<GeographicCoordinate | null>"?

Scenario: Utilizing vue.js (^3.2.13) with Typescript and Composition API in Visual Studio Code File type.ts: export class GeographicCoordinate { latitude: number; longitude: number; altitude?: number; constructor(latitude: number, longitude: numb ...

Can JSON encoding in a URL pose a risk of XSS attacks?

To ensure my application has URL-friendly capabilities, I am storing its context as a JSON within the URL. This results in something like: http://mysite.dev/myapppage/target#?context={%22attr1%22%3A{%22target_id-0%22%3A{%22value%22%3A%223%22%2C%22label%2 ...

Progressing with JavaScript: Implementing Sound Controls and Dynamic Image Switching

I am looking to create a button that, when clicked, displays a small image and plays a sound. The button should change to a different image and stop the sound when clicked again. Essentially, it functions as a "start" button that loops the sound and change ...

Experiencing issues with Firebase authentication on Nuxt app when refreshing the page for beginners

Despite my efforts of trying numerous examples and methods, I am still stuck in this situation - I have been struggling with it for the past 2 days now... The issue I am facing is that my app functions properly when I log in and click on links, but if I re ...

Removing consecutive pipe symbols in JavaScript

Looking for a way to remove excess pipe characters before a certain pattern in JavaScript. var testString="||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||f_test!!3!!||f_test!!4!!||f_test!!5!!||"; output ="||f_test!!3!!| ...

Axios AJAX request failing to pass parameter

Vuejs is my go-to frontend framework for building projects. When creating a component called ('TimeCapsy.vue'), I initiate an AJAX call to the backend in this manner: created: function () { if (verify.verify_login()) { let tok ...

Troublesome glitches in jQuery?

I'm having an issue with the following code: var buggy_brand_name = ['Baby Jogger', 'Babyzen', 'Bugaboo', 'GB', 'Icandy', 'Joie', 'Maclaren', 'Mamas&Papas', 'Ma ...

Guide on incorporating Admin LTE 3 into Nuxt.js

Is there a way to seamlessly combine adminlte 3 with Nuxt.js? Following the installation of adminlte 3 via npm, I attempted to add css and js files in nuxt.config.js. While the styles appear to be functioning correctly, the javascript is not executing as ...

React state is not refreshing as expected

I am having trouble updating the state with new employee data. The push function is not inserting the new employee data into the state. In the addPar function, I set up a console log and it shows that the data is there, but it fails to push it to the sta ...

An easy way to attach a Contextmenu to a specific element

I have implemented a scrolling feature for one of the div elements in my Application. Inside this div, there is a templated table with over 100 rows. Users are able to add or delete rows using a contextMenu. The contextMenu offers 4 options - AddTop, AddB ...

How to extract the HTML content from specific text nodes using Javascript

I have a piece of HTML that looks like this: <div id="editable_phrase"> <span data-id="42">My</span> <span data-id="43">very</span> <span data-id="1">first</span> <span data-id="21">phrase< ...

What is the process for updating button text upon clicking in Angular?

To toggle the text based on whether this.isDisabled is set to false or true, you can implement a function that changes it when the button is clicked. I attempted to use this.btn.value, but encountered an error. import { Component } from '@angular/core ...

Navigate the Angular interceptor route to display a 404 error page when clicking on a `<a href="#">` tag

When using href="#" as a placeholder in html, I encountered an issue where Angular was unable to recognize it and would route to the 404 page despite having the following configuration in the module. How can this problem be resolved? .config( function m ...