A production-ready, full-stack application for soil health monitoring and analysis with JWT authentication, real-time mapping, and personalized fertilizer recommendations.
- π Secure Authentication: JWT-based authentication with bcrypt password hashing
- πΊοΈ Interactive Maps: Leaflet-based soil health visualization with NPK data
- π Real-time Analytics: District-wise soil health dashboard with Chart.js
- πΎ Crop Recommendations: Personalized fertilizer recommendations based on soil tests
- π± Responsive Design: Modern, mobile-first UI with stunning animations
- π API Integration: Ready for data.gov.in API integration
Our map provides a high-level overview of soil health across India.
- Comprehensive Nutrient Visualization: Now supports visualization for Nitrogen (N), Phosphorus (P), Potassium (K), Organic Carbon (OC), and Soil pH.
- Dynamic Legend & Styling: The map legend and color schemes adapt automatically based on the selected nutrient.
- Advanced Popups: Interactive bar charts in popups show the full soil profile for each district.
- Real-time Map Statistics: A new overlay displays the total number of districts and samples analyzed in the current view.
- Enhanced Sidebar: Detailed district information panel with status indicators for all major soil parameters.
- Real-time Recommendations: Get fertilizer doses (Urea, DAP, MOP) based on your soil test results.
- State-wise Filtering: Easily filter map data by state.
- Modern UI: Dark mode support and responsive design for mobile devices.
- π API Integration: Ready for data.gov.in API integration
The following major enhancements were recently contributed:
- Advanced Map Visuals: Integrated district search, multi-layer support (Satellite/Terrain), and interactive popup charts.
- Soil Health Wizard: Replaced static forms with a multi-step recommendation wizard and Radar Chart analysis.
- Sustainability Scoring: Added dynamic scoring to promote eco-friendly fertilizer balance.
- Universal Dark Mode: Implemented site-wide dark mode with persistence.
- Mobile First Design: Fully responsive navigation and touch-optimized components.
- Map Visibility & Data Enhancements (8 Commits):
- Schema Expansion: Added support for Phosphorus, Potassium, and Organic Carbon analytics.
- API Hardening: Extended Map API to serve multi-nutrient GeoJSON data.
- Dynamic Legend Engine: Implemented smart legend scaling based on selected soil parameters.
- Advanced Multi-Nutrient Layers: Added toggles for N, P, K, OC, and pH visualizations.
- Interactive Popup Charts: Integrated real-time bar charts for detailed district soil profiles.
- Map Statistics Overlay: Added dynamic district and sample counter overlay for real-time summaries.
- Enhanced District Insights: Expanded the information panel with status-aware nutrient boxes.
- Global Polish: Refactored mapping logic for improved performance and data integrity.
The core backend logic was recently hardened and architecturally improved:
- Secure Hashing Migration: Successfully migrated from SHA-256 to BCrypt with automatic salting for industry-standard password security.
- Declarative Validation: Integrated Jakarta Validation framework across all API entry points to ensure strict data integrity.
- Service Layer Pattern: Decoupled business logic into dedicated AuthService and SoilService classes, improving testability and separation of concerns.
- Atomic Transactions: Implemented transactional integrity in the registration workflow, ensuring multi-step database operations are either fully completed or rolled back.
- Standardized Error Handling: Added a Global Exception Handler to provide consistent, meaningful JSON error responses for all API failures.
- Micronaut 4.x framework for high performance
- PostgreSQL with PostGIS for geospatial data
- JWT token-based authentication
- RESTful API architecture
- Production-ready configuration
- Docker support
The system follows a modern, decoupled architecture:
- Backend: Built with Micronaut 4.x (Java), providing a lightweight, high-performance REST API.
- Frontend: Responsive Single Page Application (SPA) utilizing modern JavaScript and Leaflet for mapping.
- Database: PostgreSQL with PostGIS for robust spatial data handling and efficient nutrient analysis.
- Security: Stateless JWT-based authentication ensuring secure access across all endpoints.
The application now features a robust connection between the Leaflet-based map and the PostgreSQL/PostGIS backend:
- Dynamic GeoJSON Generation: Districts are fetched in real-time from the database with integrated soil health metrics.
- PostGIS Integration: Spatial boundaries (MultiPolygons) are handled via PostGIS, ensuring precise geographical mapping.
- Multi-level Fallback: If specific district data is missing, the system intelligently falls back to state averages for fertilizer recommendations.
- Rich Visualization: Supports visualization of Nitrogen, Phosphorus, Potassium, Organic Carbon, and pH levels with interactive charts.
- State Statistics: Real-time aggregation of state-wise soil health distribution (High/Medium/Low).
- Java 17 or higher
- PostgreSQL 14+ with PostGIS extension
- Gradle 8.x
- Node.js (optional, for frontend development)
- Clone the repository
git clone https://github.com/hedoescode-mayank/Interactive-Soil-Health-Map.git
cd Interactive-Soil-Health-Map- Set up PostgreSQL
# Create database
createdb ishm
# Enable PostGIS
psql ishm -c "CREATE EXTENSION IF NOT EXISTS postgis;"
# Run schema
psql ishm < src/main/resources/schema-enhanced.sql- Configure environment variables
# Create .env file
cat > .env << EOF
DB_URL=jdbc:postgresql://localhost:5432/ishm
DB_USER=your_db_user
DB_PASSWORD=your_db_password
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production-min-256-bits
DATA_GOV_API_KEY=your_data_gov_api_key_here
SOIL_HEALTH_RESOURCE_ID=your_resource_id
EOF- Build and run
# Build the application
./gradlew clean build
# Run the application
./gradlew run
# Or run the JAR
java -jar build/libs/Interactive_Soil_Health_Map-1.0.0.jar- Access the application
Open browser: http://localhost:8080
| Variable | Description | Default |
|---|---|---|
DB_URL |
PostgreSQL connection URL | jdbc:postgresql://localhost:5432/ishm |
DB_USER |
Database username | ishm |
DB_PASSWORD |
Database password | ishm |
JWT_SECRET |
JWT signing secret (min 256 bits) | changeMeInProduction... |
JWT_EXPIRATION |
Token expiration in seconds | 86400 (24 hours) |
DATA_GOV_API_KEY |
Data.gov.in API key | - |
SOIL_HEALTH_RESOURCE_ID |
Soil health resource ID | - |
CORS_ALLOWED_ORIGINS |
Allowed CORS origins | * |
LOG_LEVEL_APP |
Application log level | INFO |
- development: Debug logging, relaxed CORS
- production: Optimized for production, strict security
- docker: Configured for Docker deployment
- test: Test configuration with in-memory database
Activate profile:
MICRONAUT_ENVIRONMENTS=production java -jar app.jarPOST /api/auth/register
Content-Type: application/json
{
"username": "farmer123",
"password": "secure_password",
"postalCode": "110001",
"fullName": "John Farmer",
"phone": "9876543210"
}
Response 200 OK:
{
"success": true,
"message": "Registration successful",
"farmer": {
"id": 1,
"username": "farmer123",
"postalCode": "110001",
"district": "Delhi",
"state": "Delhi"
}
}POST /api/auth/login
Content-Type: application/json
{
"username": "farmer123",
"password": "secure_password"
}
Response 200 OK:
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"farmer": {
"id": 1,
"username": "farmer123",
"district": "Delhi",
"state": "Delhi"
}
}PUT /api/auth/update-password
Content-Type: application/json
Authorization: Bearer <token>
{
"oldPassword": "current_password",
"newPassword": "new_secure_password"
}
Response 200 OK:
{
"success": true,
"message": "Password updated successfully"
}GET /api/map/districts?state=Delhi
Response 200 OK:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": { ... },
"properties": {
"district_name": "Delhi",
"state_name": "Delhi",
"nitrogen_avg": 110,
"nitrogen_status": "Low",
"phosphorus_avg": 18,
"phosphorus_status": "Medium",
"potassium_avg": 300,
"potassium_status": "High"
}
}
]
}GET /api/map/stats/Delhi
Response 200 OK:
{
"state": "Delhi",
"district_count": 11,
"avg_nitrogen": 110.5,
"avg_phosphorus": 18.2,
"avg_potassium": 300.1,
"total_samples": 15234,
"npk_distribution": {
"nitrogen": { "low": 8, "medium": 2, "high": 1 },
"phosphorus": { "low": 3, "medium": 6, "high": 2 },
"potassium": { "low": 1, "medium": 5, "high": 5 }
}
}POST /api/recommendations/calculate
Content-Type: application/json
{
"state": "Delhi",
"district": "Delhi",
"crop": "wheat",
"season": "rabi",
"nitrogen": 250,
"phosphorus": 15,
"potassium": 180,
"ph": 7.2
}
Response 200 OK:
{
"nitrogenStatus": "Low",
"phosphorusStatus": "Medium",
"potassiumStatus": "Medium",
"ureaDose": 150.5,
"dapDose": 100.2,
"mopDose": 80.0,
"schedule": {
"basal": "Apply 50% N, full P and K at sowing",
"firstTopdress": "30-35 days after sowing",
"secondTopdress": "60-65 days after sowing"
},
"tips": [
"Apply fertilizers when soil has adequate moisture",
"Avoid application during heavy rain"
]
}GET /api/dashboard/summary?state=Delhi&year=2025
Authorization: Bearer <token>
Response 200 OK:
{
"metrics": {
"districtsCovered": 127,
"totalSamples": 4150000,
"avgSoilHealth": 6.8,
"farmersBenefited": 2300000
},
"npkTrends": { ... },
"stateDistribution": [ ... ],
"districtSummary": [ ... ]
}version: '3.8'
services:
db:
image: postgis/postgis:14-3.3
environment:
POSTGRES_DB: ishm
POSTGRES_USER: ishm
POSTGRES_PASSWORD: ishm
volumes:
- postgres_data:/var/lib/postgresql/data
- ./schema-enhanced.sql:/docker-entrypoint-initdb.d/init.sql
ports:
- "5432:5432"
app:
build: .
ports:
- "8080:8080"
environment:
DB_URL: jdbc:postgresql://db:5432/ishm
DB_USER: ishm
DB_PASSWORD: ishm
JWT_SECRET: ${JWT_SECRET}
MICRONAUT_ENVIRONMENTS: docker
depends_on:
- db
volumes:
postgres_data:Run:
docker-compose up -d./gradlew dockerBuild
docker run -p 8080:8080 soil-health-monitor:1.0.0- Change Default JWT Secret: Always use a strong, random secret in production
- Use HTTPS: Enable SSL/TLS in production environments
- Secure Database: Use strong passwords and restrict database access
- Environment Variables: Never commit secrets to version control
- Rate Limiting: Implement rate limiting for API endpoints
- Input Validation: All inputs are validated server-side
- CORS: Configure allowed origins properly
- farmers: User authentication and profile data
- districts: Geographic boundaries with PostGIS geometry
- soil_health_data: NPK levels and soil parameters
- crop_recommendations: Crop-specific nutrient requirements
- states: State-level geographic data
- Geographic indexes (GiST) for spatial queries
- B-tree indexes on foreign keys and frequently queried columns
- Composite indexes for common query patterns
# Run all tests
./gradlew test
# Run specific test class
./gradlew test --tests AuthControllerTest
# Run with coverage
./gradlew test jacocoTestReport- Database: Connection pooling with HikariCP (max 50 connections)
- Caching: TTL-based caching for district and statistics data
- Lazy Loading: Efficient data fetching with JOIN queries
- CDN: Serve static assets via CDN in production
- Compression: Enable GZIP compression for API responses
To integrate with India's Open Data platform:
- Register at https://data.gov.in
- Get API key and resource ID for soil health data
- Set environment variables:
DATA_GOV_API_KEY=your_api_key
SOIL_HEALTH_RESOURCE_ID=resource_id
DATA_GOV_API_ENABLED=true- The system will automatically enrich local data with government datasets
Issue: Database connection failed
# Check PostgreSQL is running
systemctl status postgresql
# Verify connection
psql -U ishm -d ishm -h localhostIssue: JWT token invalid
- Ensure JWT_SECRET is set and consistent across restarts
- Check token expiration time
- Verify Authorization header format:
Bearer <token>
Issue: Map not loading
- Check browser console for errors
- Verify API endpoints are accessible
- Ensure database has district geometry data
This project is licensed under the MIT License - see LICENSE file for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
For support and queries:
- Email: support@soilhealth.gov.in
- Issues: GitHub Issues
- Documentation: https://docs.soilhealth.gov.in
- Ministry of Agriculture & Farmers Welfare, Government of India
- OpenStreetMap for map tiles
- data.gov.in for open datasets
- PostgreSQL and PostGIS communities
Built with β€οΈ for Indian farmers