How can I dynamically retrieve GeoJSON data based on a given country or state name?

I am developing a Next.js application where I display a map on the dashboard using the react-leaflet package. When the dashboard page loads, a GET API is called, returning an array of strings, which are either country names or state names based on the user’s role. For example, if the user role is ADMIN, the API returns an array of country names like [‘India’, ‘Australia’, ‘Singapore’, ‘United States’, ‘Germany’]. If the user role is AGENT, the API returns an array of state names like [‘New Delhi’, ‘Alabama’, ‘Sakha Republic’, ‘Hiroshima’].

I need to shade the corresponding countries or states on the map with a specific color, as shown in the image below:

Note: The image shows a zoomed-in view, but the entire world map should be visible. If an ADMIN is logged in, the map should be shaded based on country names. If an AGENT is logged in, it should be shaded based on state names received from the API.

CURRENT PROCEDURE :

Currently, I am using two GeoJSON files: one for countries (world_countries.json) and another for India states (Indian_States.json). The structure of the world_countries.json file is as follows:

world_countries.json :

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": "CHL",
      "properties": {
        "name": "Chile"
      },
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [37368, 63698],
          ...
        ]
      }
    },
    ...
  ]
}

In my Dashboard.tsx component, I shade the areas using the attribute as shown below:

Dashboard.tsx

import React, { useMemo } from 'react';
import { MapContainer, TileLayer, GeoJSON, Marker, Popup } from 'react-leaflet';
import { Icon } from 'leaflet';
import 'leaflet/dist/leaflet.css';
import indiaGeoJson from './Indian_States.json';
import worldCountrysJson from './world_countries.json';
import testJSon from './test.json';
import { useRegion } from '@/helper/providers/DashboardRegionProvider';
import { regionTabs } from '@/helper/constants/dashboard';
import { useSidebar } from '@/helper/providers';
import { ORGANIZATION_TYPES } from '@/server/config/constant';
import { Country, State, City } from 'country-state-city';

const RegionMap = () => {
  const { transactionLocation, activeTab } = useRegion();
  const { currentUser } = useSidebar();
  const isOrganizationTypeNotCustomer = useMemo<boolean>(
    () => ORGANIZATION_TYPES.includes(currentUser?.organizationType ?? ''),
    [currentUser?.organizationType],
  );
  const LocaionMarkerIcon = new Icon({
    iconUrl: '/images/dashboard/location_marker.svg',
  });

  const COUNTRIES_LIST = Country.getAllCountries();
  const STATES_LIST = State.getAllStates();

  // Getting transactionStatesOrCountries coordinates from GeoJson files to shade them with color
  const transactionCountriesOrStates = useMemo(() => {
    const GeoJSON = isOrganizationTypeNotCustomer
      ? worldCountrysJson
      : indiaGeoJson;
    if (GeoJSON && (GeoJSON as any)?.features) {
      return (GeoJSON as any).features.filter((feature: any) => {
        const locationName = isOrganizationTypeNotCustomer
          ? feature.properties.name
          : feature.properties.NAME_1;
        return (
          feature.properties &&
          transactionLocation?.includes(
            (locationName as string).toLocaleLowerCase().replaceAll(' ', ''),
          )
        );
      });
    }
    return [];
  }, [transactionLocation]);

  // Updating transactionLocations Array with latitude , longitude and name of the city in them to pin the city location on map
  const updatedTransactionLocation = transactionLocation?.map((location) => {
    let cityResults: any = {};
    if (isOrganizationTypeNotCustomer) {
      const countryDetail = COUNTRIES_LIST.filter((countryDetail) => {
        const countryName = countryDetail.name
          .toLowerCase()
          .replaceAll(' ', '');
        return countryName === location.toLocaleLowerCase().replaceAll(' ', '');
      })[0];
      cityResults = City.getCitiesOfCountry(countryDetail?.isoCode)?.[0];
    } else {
      const stateDetail = STATES_LIST.filter((stateDetail) => {
        const name = stateDetail.name.toLowerCase().replaceAll(' ', '');
        return name === location.toLocaleLowerCase().replaceAll(' ', '');
      })[0];
      cityResults = City.getCitiesOfState(
        stateDetail.countryCode,
        stateDetail.isoCode,
      )[0];
    }
    const { latitude, longitude, name } = cityResults;
    return {
      locationName: location,
      cityLocation: { latitude, longitude, name },
    };
  });

  // Updating transactionCountriesOrStates to make the statevalue to do both shading and pointing location
  const updatedTransactionCountriesOrStates = transactionCountriesOrStates.map(
    (feature: any) => {
      const locationName = isOrganizationTypeNotCustomer
        ? feature.properties.name
        : feature.properties.NAME_1;

      const markerLocation = updatedTransactionLocation?.filter(
        (trandactionLocation) => {
          return (
            trandactionLocation?.locationName
              .toLowerCase()
              .replaceAll(' ', '') ===
            locationName?.toLowerCase().replaceAll(' ', '')
          );
        },
      )[0];

      return {
        feature,
        markerLocation: markerLocation?.cityLocation,
      };
    },
  );

  return (
    <div className="relative z-10 h-full w-full">
      <MapContainer
        center={[17.385044, 78.486671]}
        zoom={4}
        style={{ height: '100%', width: '100%' }}
        className="rounded-2xl border-none focus:border-none"
      >
        <TileLayer
          url="https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png"
          attribution='© <a href="https://carto.com/attributions">CARTO</a>'
        />
        {updatedTransactionCountriesOrStates.map(
          (transactionState: any, index: any) => {
            return (
              <>
                <GeoJSON
                  key={index}
                  data={transactionState.feature}
                  style={() => ({
                    fillColor: regionTabs[activeTab].bgColor,
                    color: 'white',
                    weight: 0.5,
                    fillOpacity: 1,
                  })}
                />

                <Marker
                  position={[
                    transactionState.markerLocation.latitude,
                    transactionState.markerLocation.longitude,
                  ]}
                  icon={LocaionMarkerIcon}
                >
                  <Popup>{transactionState.markerLocation.name}</Popup>
                </Marker>
              </>
            );
          },
        )}
      </MapContainer>
    </div>
  );
};

export default RegionMap;

Problems:

Problem 1: My world_countries.json file does not include all countries, and maintaining a large GeoJSON file in the application is impractical.

Problem 2: Currently, I have only added a GeoJSON file for Indian states. If the API response includes states from other countries, they will not be shaded on the map. Adding GeoJSON files for all countries is not a feasible solution.

Request:

How can I handle this situation effectively? Is there a way to dynamically retrieve the corresponding GeoJSON files from any open-source APIs or other reliable sources? Any guidance or suggestions would be greatly appreciated.

Thanks in advance!

7

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật