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