Skip to content

Montimage/markmap

Repository files navigation

React Mark Map Component

A powerful and flexible React component library for displaying marked points on interactive Leaflet maps with color-coded point types and labels. Perfect for building store locators, event maps, asset tracking, and data visualization applications.

Features

🗺️ Interactive Maps - Built on Leaflet for smooth interaction
🎨 Color-coded Points - Automatic color assignment by point type
🏷️ Custom Labels - Display meaningful names for each point
Legend Support - Optional legend showing point types
🎯 Auto-fitting - Map automatically adjusts to show all points
💬 Popup Details - Click points to see detailed information
Lightweight - Pure JavaScript, no TypeScript dependencies
📱 Responsive - Works seamlessly on desktop and mobile devices

Installation

npm install markmap

Quick Start

import React from 'react';
import { MarkMap } from 'markmap';

function App() {
  const points = [
    { lat: 46.013, lng: 13.252, label: 'Pizza Palace', point_type: 'restaurant' },
    { lat: 46.012, lng: 13.250, label: 'Grand Hotel', point_type: 'hotel' },
    { lat: 46.014, lng: 13.253, label: 'City Park', point_type: 'park' }
  ];

  return (
    <div>
      <h1>My Mark Map App</h1>
      <MarkMap 
        points={points}
        height="500px"
        showLegend={true}
      />
    </div>
  );
}

export default App;

Project Structure

The MarkMap component library is organized with a clean, modular structure:

markmap/
├── src/                  # Source code
│   ├── MarkMap.jsx       # Main component implementation
│   └── index.js          # Entry point for exports
├── example/              # Example application
│   ├── src/
│   │   ├── App.jsx       # Demo application
│   │   ├── pointsData.js # Sample data
│   │   └── index.js      # Example app entry point
│   └── public/           # Static assets for example
├── dist/                 # Built distribution files (generated)
├── node_modules/         # Dependencies
├── package.json          # Project configuration
└── README.md             # Documentation

Core Files

  • src/MarkMap.jsx: The main component that renders the interactive map with markers
  • src/index.js: Exports the component for use in other applications
  • example/src/App.jsx: Demonstrates how to use the component with various options

Updating the Component

To make improvements to the MarkMap component:

  1. Understand the Component Structure:

    • The main component is in src/MarkMap.jsx
    • It uses React hooks for state management
    • Leaflet is used for the underlying map functionality
  2. Making Changes:

    • For small changes, modify the existing component while maintaining its API
    • For larger features, consider creating separate utility functions or sub-components
    • Keep files under 300 lines for better maintainability
    • Follow the existing patterns for state management and event handling
  3. Common Modification Points:

    • Marker Styling: Update the createCustomIcon function
    • Map Controls: Add new controls in the main render function
    • Data Handling: Modify how points are processed in the updateMarkers function
    • UI Components: Update the legend or add new UI elements
  4. Example:

    // Adding a new prop for custom marker size
    const MarkMap = ({ 
      points = [],
      height = '400px',
      width = '100%',
      center = null,
      zoom = 13,
      colorScheme = {},
      showLegend = true,
      markerSize = 30  // New prop
    }) => {
      // Update the createCustomIcon function to use the markerSize prop
      const createCustomIcon = (color, pointType) => {
        return L.divIcon({
          className: 'custom-map-marker',
          html: `<div style="background-color: ${color}; width: ${markerSize}px; height: ${markerSize}px;"></div>`,
          iconSize: [markerSize, markerSize],
          iconAnchor: [markerSize/2, markerSize],
          popupAnchor: [0, -markerSize]
        });
      };
      
      // Rest of the component...
    }

Testing Your Changes

Setting Up the Test Environment

  1. Install Dependencies:

    npm install
  2. Run Tests:

    npm test
  3. Test Coverage:

    npm test -- --coverage
  4. Security Audit:

    npm run audit

Testing Strategies

  1. Manual Testing with the Example App:

    # Navigate to the example directory
    cd example
    
    # Install dependencies
    npm install
    
    # Start the example app
    npm start

    This will launch the example application where you can interact with your component and verify your changes work as expected.

  2. Writing Tests:

    Create test files in a __tests__ directory or with a .test.js suffix:

    // src/__tests__/MarkMap.test.js
    import React from 'react';
    import { render, screen, fireEvent } from '@testing-library/react';
    import { MarkMap } from '../index';
    
    describe('MarkMap Component', () => {
      const mockPoints = [
        { lat: 46.013, lng: 13.252, label: 'Test Point', point_type: 'test' }
      ];
      
      test('renders without crashing', () => {
        render(<MarkMap points={mockPoints} />);
        // Assert component rendered successfully
      });
      
      test('displays legend when showLegend is true', () => {
        render(<MarkMap points={mockPoints} showLegend={true} />);
        // Assert legend is visible
      });
      
      test('does not display legend when showLegend is false', () => {
        render(<MarkMap points={mockPoints} showLegend={false} />);
        // Assert legend is not visible
      });
    });
  3. Testing Edge Cases:

    • Empty points array
    • Invalid coordinates
    • Missing required props
    • Boundary conditions for zoom levels
    • Different color schemes

Debugging Tips

  1. Console Logging: Add temporary console.log() statements to trace component behavior

  2. React DevTools: Use React DevTools browser extension to inspect component state and props

  3. Error Boundary: The component includes an error boundary (MarkMapErrorBoundary) that catches and displays errors

  4. Performance Testing: Use React's built-in Profiler or browser performance tools to identify bottlenecks

Deployment and Version Control

Git Workflow

When working on improvements to the library, follow these Git best practices:

# Before starting work, ensure you're up to date
git pull origin main

# Create a new branch for your feature
git checkout -b feature/your-feature-name

# Make frequent, small commits with clear messages
git commit -m "feat: add clustering support for large datasets"

# Push your changes
git push origin feature/your-feature-name

Commit Message Guidelines

Use conventional commit messages to make the changelog more readable:

  • feat: - New features
  • fix: - Bug fixes
  • docs: - Documentation changes
  • style: - Code style changes (formatting, etc)
  • refactor: - Code changes that neither fix bugs nor add features
  • perf: - Performance improvements
  • test: - Adding or updating tests

Deployment Process

After making and testing your changes:

  1. Update Version:

    # For a patch update (bug fixes)
    npm version patch
    
    # For a minor update (new features)
    npm version minor
    
    # For a major update (breaking changes)
    npm version major
  2. Build the Library:

    npm run build
  3. Verify the Build: Check that the distribution files were generated correctly in the dist/ directory.

  4. Create a Pull Request: Submit your changes for review through GitHub's pull request system with a clear description of your changes.

  5. Release: Once merged, the library can be published to npm:

    npm publish

Props

Prop Type Default Description
points Array<Point> [] Array of points to display on the map
height string '400px' Map container height
width string '100%' Map container width
center {lat: number, lng: number} Auto-calculated Map center coordinates
zoom number 13 Initial map zoom level
colorScheme Object Auto-generated Custom colors for point types
showLegend boolean true Show/hide the legend

Point Object Structure

{
  lat: number,           // Latitude coordinate (required)
  lng: number,           // Longitude coordinate (required)  
  label: string,         // Display name (required)
  point_type: string     // Type for color grouping (required)
}

Advanced Usage

Custom Color Schemes

const colorScheme = {
  restaurant: '#FF6B6B',  // Red
  hotel: '#4ECDC4',       // Teal  
  park: '#00B894',        // Green
  hospital: '#FF7675',    // Light Red
  cafe: '#FDCB6E'         // Yellow
};

<MarkMap 
  points={points}
  colorScheme={colorScheme}
  height="600px"
  width="800px"
/>

Hide Legend

<MarkMap 
  showLegend={false}
  height="300px"
/>

Control Map Center and Zoom

<MarkMap 
  points={points}
  center={{ lat: 40.7128, lng: -74.0060 }}
  zoom={12}
  height="500px"
/>

Integration with Custom UI

function CustomMapApp() {
  return (
    <div style={{ 
      backgroundColor: '#f8f9fa', 
      padding: '20px', 
      borderRadius: '10px' 
    }}>
      <h2>Location Finder</h2>
      <MarkMap 
        points={myPoints}
        height="500px"
        showLegend={true}
      />
      />
    </div>
  );
}

Development

To set up the development environment:

# Clone the repository
git clone https://github.com/montimage/markmap.git

# Install dependencies
npm install

# Start development server
npm run dev

# Build the library
npm run build

Contributing

We welcome contributions to improve the quality and functionality of this library! Here's how you can help:

Development Workflow

  1. Fork the repository and create a new branch for your feature or bugfix
  2. Set up your development environment following the instructions above
  3. Make your changes following our coding standards
  4. Test your changes thoroughly
  5. Submit a pull request with a clear description of your changes

Code Quality Improvements

Here are some areas where you can help improve the library:

Component Structure

  • Refactor the component into smaller, more focused sub-components
  • Improve prop validation and default values
  • Add TypeScript type definitions for better developer experience

Performance Optimization

  • Implement memoization for expensive calculations
  • Optimize marker rendering for large datasets
  • Reduce unnecessary re-renders

Features

  • Add clustering support for handling large numbers of points
  • Implement custom marker styling options
  • Add support for GeoJSON data
  • Create additional map controls (zoom, fullscreen, etc.)

Accessibility

  • Improve keyboard navigation
  • Add ARIA attributes for better screen reader support
  • Ensure proper focus management
  • Add high contrast mode

Testing Guidelines

When contributing, please ensure your code is properly tested:

# Run tests
npm test

# Run tests with coverage
npm test -- --coverage

Consider adding tests for:

  • Component rendering
  • User interactions
  • Edge cases (empty data, invalid coordinates)
  • Performance benchmarks

Documentation

Good documentation is crucial for library adoption:

  • Update JSDoc comments for all components and functions
  • Add usage examples for different scenarios
  • Document props, methods, and events
  • Create storybook examples (if applicable)

Code Style

This project follows these coding standards:

  • Use functional components with hooks
  • Follow React best practices
  • Use consistent naming conventions
  • Write meaningful comments
  • Format code with Prettier

Submitting Changes

  1. Ensure your code passes all tests
  2. Update documentation if needed
  3. Add yourself to the contributors list
  4. Create a pull request with a clear description of changes

Browser Requirements

  • Modern browsers with ES6+ support
  • Geolocation API support for GPS features
  • Internet connection for map tiles

Dependencies

This component has minimal peer dependencies:

  • React ≥16.8.0
  • React DOM ≥16.8.0

The component automatically loads Leaflet maps library when needed, so no additional map dependencies are required.

License

MIT

Support

If you encounter any issues or have questions, please file an issue on our GitHub repository.


Made with ❤️ for the React community

About

A powerful and flexible React component library for displaying marked points on interactive Leaflet maps with color-coded point types and labels. Perfect for building store locators, event maps, asset tracking, and data visualization applications.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors