@getsoren/map

中文文档
1.11.2发布于 2026/11/09UNLICENSEDTypeScriptESM + CJS近 30 天下载 3496

A React library to easily display map with multiple tools

原始使用文档
文档目录43 节
  1. 🚀 Installation
  2. ⚙️ Requirements
  3. ✨ Features
  4. 🧩 Quick Start
  5. 🧭 Components Overview
  6. MapProvider
  7. MapView / MarkerMap
  8. Specialized Components
  9. 🧱 Props Reference
  10. MapView Props
  11. Marker Props ( MarkerProps )
  12. Itinerary Props ( itineraryParams )
  13. Nearest Marker Search ( findNearestMarker )
  14. Isochrone Props ( isochrone )
  15. GeoJSON Features ( features )
  16. 🧠 Advanced Use Cases
  17. 🧭 Real-time GPS Tracking
  18. 🔄 Dynamic Data with React Query
  19. 🎨 Custom Marker Components
  20. 🗺️ Multi-Route Comparison
  21. 🎯 Click-to-Add Markers
  22. 🚗 Combined Routing & Nearest Search
  23. 💡 Tips & Best Practices
  24. Performance Optimization
  25. UX Improvements
  26. Routing Best Practices
  27. 🧑‍💻 Development
  28. Prerequisites
  29. Setup
  30. Available Scripts
  31. Project Structure
  32. Testing
  33. Contributing
  34. 📘 Documentation & Examples
  35. 📦 Publishing & Deployment
  36. Publish to npm
  37. Deploy Sandbox to GitHub Pages
  38. 🔧 Troubleshooting
  39. Common Issues
  40. Getting Help
  41. 📄 License
  42. 🧭 Links
  43. 🙏 Acknowledgments

🗺️ @getsoren/map

A modern, lightweight React map library built on top of Mapbox GL JS and react-map-gl. Designed for simplicity, flexibility, and visual elegance.

Easily combine markers, routes, GeoJSON features, isochrones, and nearest-point calculations — all with a declarative, type-safe API.

License


🚀 Installation

npm install @getsoren/map

or

yarn add @getsoren/map

or

bun add @getsoren/map

⚙️ Requirements

DependencyVersionPurpose
react17+ / 18+ / 19+Core React runtime
react-dom17+ / 18+ / 19+React DOM rendering
mapbox-gl≥3.0.0Map rendering engine
@getsoren/design-system≥4.0.0UI theming and components
@mui/icons-material*Material UI icons
@mui/x-license*MUI X license integration

🪶 You'll also need a Mapbox access token to render maps. Get one at mapbox.com.


✨ Features

✅ Declarative API — manage complex map interactions with simple props
✅ Markers & Popups — customizable React components or image-based icons
✅ Routing & Isochrones — visualize travel-time areas or compute optimal routes
✅ GeoJSON Layers — render vector data dynamically
✅ Nearest Marker Search — find and highlight closest points instantly
✅ Type-safe API — full TypeScript support with smart IntelliSense
✅ Responsive Design — automatically adapts to any container or screen size
✅ Built for performance — minimal re-renders, efficient map updates
✅ Multiple Routing Engines — supports both OSRM (free) and Mapbox Directions API
✅ Flexible Map Styles — works with Mapbox styles, OpenStreetMap, or custom raster tiles


🧩 Quick Start

import { MapProvider, MarkerMap } from "@getsoren/map";

const markers = [
    {
        id: 1,
        lng: 2.3522,
        lat: 48.8566,
        Tooltip: <div>Paris</div>,
        color: "primary",
        variant: "default",
    },
    {
        id: 2,
        lng: -0.1276,
        lat: 51.5074,
        Tooltip: <div>London</div>,
        color: "secondary",
        variant: "default",
    },
];

function App() {
    return (
        <MapProvider
            licenseMuiX="your-muix-license"
            licenceMapbox="your-mapbox-token"
        >
            <MarkerMap
                markers={markers}
                center={[2.3522, 48.8566]}
                zoom={5}
                fitBounds
                height={500}
                width="100%"
                onMapClick={(lng, lat, marker) => {
                    console.log("Clicked at:", lng, lat);
                    if (marker) console.log("Marker clicked:", marker);
                }}
            />
        </MapProvider>
    );
}

🧭 Components Overview

MapProvider

Wraps your map components and injects required providers (theme, tokens, MUI X license).

Required Props:

  • licenseMuiX — Your MUI X license key
  • licenceMapbox — Your Mapbox access token
<MapProvider
    licenseMuiX="your-license"
    licenceMapbox="your-token"
>
    {/* Your map components */}
</MapProvider>

MapView / MarkerMap

Main map component that handles:

  • Marker rendering with custom icons or React components
  • Interactive popups with hover/click modes
  • Automatic bounds fitting
  • Map click events
  • Responsive container sizing

Specialized Components

  • RouteMap → Draw routes between two points using OSRM or Mapbox
  • IsochroneMap → Compute and display travel-time polygons
  • FeatureMap → Display custom GeoJSON layers with styling

🧱 Props Reference

MapView Props

Core Map Props

PropTypeDefaultDescription
centerLngLatLike | number[][2.3522, 48.8566]Initial map center coordinates [lng, lat]
zoomnumber5Initial zoom level (0-22)
widthstring | number"100%"Map container width
heightstring | number300Map container height
loadingbooleanfalseShow skeleton loader
squarebooleanfalseEnforce 1:1 aspect ratio
containerStyleSxPropsundefinedCustom MUI sx styles

Map Appearance

PropTypeDefaultDescription
theme"light" | "dark""light"Map color theme
baseMapView"street" | "satellite""street"Base map layer type
mapStylestring-Custom Mapbox style URL
projectionProjectionSpecification"mercator"Map projection system

Interaction Props

PropTypeDefaultDescription
cooperativeGesturesbooleantrueRequire modifier key for zoom/pan
doubleClickZoombooleantrueEnable double-click to zoom
onMapClick(lng, lat, marker?) => void-Callback for map clicks (includes clicked marker if applicable)

Marker Props

PropTypeDefaultDescription
markersMarkerProps[][]Array of markers to display
markerImageURLstring-Custom marker icon URL
openPopupstring | numberundefinedID of marker with open popup
openPopupOnHoverbooleanfalseOpen popups on hover instead of click
popupMaxWidthstring"300px"Maximum popup width

Bounds & Animation

PropTypeDefaultDescription
fitBoundsbooleantrueAuto-fit map to show all markers
fitBoundsPaddingnumber0Padding (px) around fitted bounds
fitBoundDurationnumber500Animation duration (ms)
disableAnimationbooleanfalseDisable all animations
fitBoundsAnimationKeyunknown-Change to re-trigger fit bounds

Marker Props (MarkerProps)

PropTypeRequiredDescription
idstring | number✅Unique marker identifier
lngnumber✅Longitude coordinate
latnumber✅Latitude coordinate
TooltipReactNode-Content for popup/tooltip
IconComponentReact.ComponentType-Custom React icon component
iconPropsobject-Props passed to IconComponent
colorstring-Marker color (MUI palette)
variantstring-Marker style variant

Example with custom icon:

import LocationOnIcon from '@mui/icons-material/LocationOn';

const marker = {
  id: 1,
  lng: 2.3522,
  lat: 48.8566,
  IconComponent: LocationOnIcon,
  iconProps: { fontSize: 'large', color: 'error' },
  Tooltip: <div>Custom Icon Marker</div>
};

Itinerary Props (itineraryParams)

Draw a route between two points with customizable styling and routing engines.

PropTypeDefaultDescription
from[number, number]-Route starting point [lng, lat]
to[number, number]-Route ending point [lng, lat]
profile"driving" | "walking" | "cycling""driving"Transportation mode
engine"OSRM" | "Mapbox""OSRM"Routing service to use
itineraryLineStylePartial<ItineraryLineStyle>{ color: "#3b82f6", width: 4, opacity: 0.8 }Route line appearance
initialRouteFeature<LineString>-Precomputed GeoJSON route
onRouteComputed(route) => void-Callback fired when route is computed
itineraryLabelReactNode-Label displayed along the route (e.g., "12 min")

Example:

<MapView
  itineraryParams={{
    from: [2.3522, 48.8566], // Paris
    to: [-0.1276, 51.5074],   // London
    profile: "driving",
    engine: "OSRM",
    itineraryLineStyle: {
      color: "#10b981",
      width: 5,
      opacity: 0.9
    },
    itineraryLabel: <span>Route principale</span>,
    onRouteComputed: (route) => {
      console.log("Route computed:", route);
    }
  }}
/>

Nearest Marker Search (findNearestMarker)

Find and highlight the closest marker to a given point within a maximum distance.

PropTypeDefaultDescription
origin[number, number]-Starting point for search [lng, lat]
destinationsArray<{id, lng, lat}>-Candidate destinations
maxDistanceMetersnumber-Maximum search radius in meters
profile"driving" | "walking" | "cycling""driving"Routing profile for distance calculation
engine"OSRM" | "Mapbox""OSRM"Routing engine to use
onNearestFound(results) => void-Callback with all nearest results
initialNearestResultsNearestResult[]-Precomputed nearest results
itineraryLineStylePartial<ItineraryLineStyle>-Style override for auto-generated itinerary

NearestResult Type:

interface NearestResult {
  id: number | string;
  point: [number, number]; // [lng, lat]
  distance: number; // in meters
  routeFeature?: Feature<LineString> | null;
}

Example:

<MapView
  findNearestMarker={{
    origin: [2.3522, 48.8566],
    destinations: markers.map(m => ({ 
      id: m.id, 
      lng: m.lng, 
      lat: m.lat 
    })),
    maxDistanceMeters: 5000,
    profile: "walking",
    engine: "OSRM",
    onNearestFound: (results) => {
      console.log(`Found ${results.length} markers within range`);
      results.forEach(r => {
        console.log(`Marker ${r.id} at ${r.distance}m`);
      });
    }
  }}
/>

Isochrone Props (isochrone)

Compute and display areas reachable within specific time intervals.

PropTypeDefaultDescription
origin[number, number]-Center point for isochrone [lng, lat]
profile"driving" | "walking" | "cycling""driving"Transportation mode
intervalsnumber[][5, 10, 15]Time intervals in minutes
onIsochroneLoaded(data) => void-Callback with GeoJSON result

Example:

<MapView
  isochrone={{
    origin: [2.3522, 48.8566],
    profile: "driving",
    intervals: [5, 10, 15, 20], // 5, 10, 15, 20 minutes
    onIsochroneLoaded: (geojson) => {
      console.log("Isochrone data:", geojson);
    }
  }}
/>

GeoJSON Features (features)

Display custom vector features like polygons, lines, or points.

PropTypeDescription
featuresFeature | Feature[] | FeatureCollectionGeoJSON data to render

Example:

<MapView
  features={{
    type: "Feature",
    geometry: {
      type: "LineString",
      coordinates: [
        [2.3, 48.8],
        [2.4, 48.9],
        [2.5, 48.85]
      ]
    },
    properties: {
      color: "#ef4444"
    }
  }}
/>

🧠 Advanced Use Cases

🧭 Real-time GPS Tracking

function LiveTracking() {
  const [position, setPosition] = useState([2.3522, 48.8566]);
  
  useEffect(() => {
    const watchId = navigator.geolocation.watchPosition((pos) => {
      setPosition([pos.coords.longitude, pos.coords.latitude]);
    });
    return () => navigator.geolocation.clearWatch(watchId);
  }, []);

  return (
    <MapView
      markers={[{
        id: 'current',
        lng: position[0],
        lat: position[1],
        Tooltip: <div>You are here</div>
      }]}
      center={position}
      zoom={15}
      fitBounds={false}
    />
  );
}

🔄 Dynamic Data with React Query

import { useQuery } from '@tanstack/react-query';

function DynamicMarkers() {
  const { data: markers } = useQuery({
    queryKey: ['locations'],
    queryFn: fetchLocations,
    refetchInterval: 5000 // Refresh every 5s
  });

  return (
    <MapView
      markers={markers}
      fitBounds
      fitBoundsAnimationKey={markers?.length}
    />
  );
}

🎨 Custom Marker Components

function CustomMarker({ isActive, count }) {
  return (
    <Box
      sx={{
        width: 40,
        height: 40,
        borderRadius: '50%',
        bgcolor: isActive ? 'success.main' : 'grey.500',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'white',
        fontWeight: 'bold',
        border: '2px solid white',
        boxShadow: 2
      }}
    >
      {count}
    </Box>
  );
}

<MapView
  markers={[{
    id: 1,
    lng: 2.3522,
    lat: 48.8566,
    IconComponent: CustomMarker,
    iconProps: { isActive: true, count: 5 }
  }]}
/>

🗺️ Multi-Route Comparison

<MapView
  features={[
    {
      type: "Feature",
      geometry: {
        type: "LineString",
        coordinates: route1
      },
      properties: { color: "#3b82f6" }
    },
    {
      type: "Feature",
      geometry: {
        type: "LineString",
        coordinates: route2
      },
      properties: { color: "#ef4444" }
    }
  ]}
/>

🎯 Click-to-Add Markers

function InteractiveMap() {
  const [markers, setMarkers] = useState([]);

  const handleMapClick = (lng, lat) => {
    setMarkers(prev => [...prev, {
      id: Date.now(),
      lng,
      lat,
      Tooltip: <div>Point {markers.length + 1}</div>
    }]);
  };

  return (
    <MapView
      markers={markers}
      onMapClick={handleMapClick}
    />
  );
}
function DeliveryMap() {
  const [origin] = useState([2.3522, 48.8566]);
  const [destinations] = useState([
    { id: 1, lng: 2.35, lat: 48.86 },
    { id: 2, lng: 2.36, lat: 48.85 },
    { id: 3, lng: 2.34, lat: 48.87 }
  ]);

  return (
    <MapView
      markers={destinations.map(d => ({
        id: d.id,
        lng: d.lng,
        lat: d.lat,
        Tooltip: <div>Destination {d.id}</div>
      }))}
      findNearestMarker={{
        origin,
        destinations,
        maxDistanceMeters: 10000,
        profile: "driving",
        engine: "OSRM",
        itineraryLineStyle: {
          color: "#22c55e",
          width: 4,
          opacity: 0.8
        },
        onNearestFound: (results) => {
          console.log("Nearest destinations:", results);
        }
      }}
    />
  );
}

💡 Tips & Best Practices

Performance Optimization

  • Memoize marker data to prevent unnecessary re-renders
  • Use fitBoundsAnimationKey to control when bounds recalculate
  • Disable animations for large datasets: disableAnimation={true}
  • Debounce dynamic updates when tracking real-time data
  • Use initialRoute and initialNearestResults to avoid redundant API calls

UX Improvements

  • Combine openPopupOnHover and disableAnimation for smooth interactions
  • Use fitBoundsPadding to ensure markers aren't at screen edges
  • Set appropriate popupMaxWidth for mobile responsiveness
  • Provide visual feedback with custom IconComponent states
  • Use itineraryLabel to display route duration or distance

Routing Best Practices

  • Use OSRM (free) for basic routing needs
  • Use Mapbox for production apps requiring SLA and support
  • Cache route results with initialRoute to minimize API calls
  • Handle network errors gracefully with onRouteComputed callback
  • Combine findNearestMarker with itineraryParams for optimal routing workflows

🧑‍💻 Development

Prerequisites

  • Bun ≥1.1.0 (recommended) or Node.js 18+
  • Git

Setup

# Clone the repository
git clone https://github.com/tracktor-tech/tracktor-map.git
cd tracktor-map

# Install dependencies
bun install

# Start development sandbox
bun run sandbox
# or
bun run dev:sandbox

Available Scripts

CommandDescription
bun run sandboxStart interactive development playground
bun run buildBuild library for production
bun run build:sandboxBuild sandbox demo site
bun run deploy:sandboxDeploy sandbox to GitHub Pages
bun run lintCheck code quality and types
bun run lint:fixAuto-fix linting issues
bun run testRun test suite
bun run test:watchRun tests in watch mode
bun run versionBump version with changelog
bun run releaseBuild and publish to npm

Project Structure

@getsoren/map/
├── src/
│   ├── components/       # Reusable map and UI components (Marker, Popup, etc.)
│   ├── constants/        # Shared configuration values and styling constants
│   ├── context/          # React context providers (e.g. map state)
│   ├── features/         # Core map features (routes, isochrones, nearest, etc.)
│   ├── services/         # External APIs and utility services
│   ├── types/            # TypeScript interfaces and types
│   ├── utils/            # Generic helpers and formatting functions
│   └── main.ts           # Library entry point
│
├── sandbox/              # Development playground (example app & live demos)
│   ├── context/          # Demo context providers
│   ├── examples/         # Interactive usage examples
│   ├── features/         # Components used in the docs/demo
│   ├── public/           # Static assets (images, previews, etc.)
│   ├── App.tsx           # Sandbox root component
│   └── index.tsx         # Sandbox entry file
│
└── test/                 # Unit and integration tests

Testing

# Run all tests
bun test

# Watch mode
bun test:watch

# Run specific test file
bun test src/components/MapView.test.tsx

Contributing

We welcome contributions! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Run tests and linting (bun run test && bun run lint)
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Code Style:

  • Follow existing patterns and conventions
  • Use TypeScript for all new code
  • Add tests for new features
  • Update documentation as needed

📘 Documentation & Examples

Explore interactive examples and comprehensive API documentation:

👉 Live Documentation & Sandbox

The sandbox includes:

  • Interactive code examples
  • Live preview of all features
  • Copy-paste ready snippets
  • API reference with search

📦 Publishing & Deployment

Publish to npm

# Update version and generate changelog
bun run version

# Build and publish
bun run release

Deploy Sandbox to GitHub Pages

bun run deploy:sandbox

This will:

  1. Build the sandbox with production optimizations
  2. Generate a 404.html for client-side routing
  3. Push to the gh-pages branch
  4. Update the live documentation site

🔧 Troubleshooting

Common Issues

Map not rendering:

  • Verify your Mapbox token is valid
  • Check browser console for errors
  • Ensure mapbox-gl CSS is imported

TypeScript errors:

  • Run bun install to update type definitions
  • Check peer dependency versions match

Performance issues:

  • Reduce marker count or use clustering
  • Disable animations for large datasets
  • Memoize marker data
  • Use initialRoute and initialNearestResults for cached data

Routing not working:

  • Verify coordinates are in [lng, lat] format (not lat, lng)
  • Check that routing engine is accessible
  • Ensure profile matches your use case
  • Verify maxDistanceMeters is reasonable for nearest search

Getting Help


📄 License

UNLICENSED — This package is proprietary software.
© [Tracktor — Kevin Graff]



🙏 Acknowledgments

Built with:

版本与发布记录

@getsoren/map 共发布 8 个版本,首次发布于 2026/05/16;过去 12 个月发布了 8 个版本。

版本发布日期距今
1.11.2latest2026/11/096 天前
1.11.12026/11/0511 天前
1.11.02026/06/115 个月前
1.10.02026/06/105 个月前
1.9.12026/06/105 个月前
1.9.02026/06/105 个月前

关于 @getsoren/map 的常见问题

@getsoren/map 是什么?

A React library to easily display map with multiple tools

如何安装 @getsoren/map?

在项目目录运行 npm install @getsoren/map,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^17.0.0 || ^18.0.0 || ^19.0.0)、mapbox-gl(>=3.0.0)、react-dom(^17.0.0 || ^18.0.0 || ^19.0.0)、@mui/x-license(*)、@getsoren/react-utils(>=1.0.0)、@getsoren/design-system(>=4.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@getsoren/map 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@getsoren/map 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@getsoren/map 可以商用吗?

@getsoren/map 使用 UNLICENSED 许可。作者声明为 UNLICENSED,即不授予公开使用许可(与公共领域的 Unlicense 不同)。使用前需获得作者授权。以上为概括,不构成法律意见,请以许可原文为准。

@getsoren/map 的下载量有多少?

根据 npm 官方下载统计,@getsoren/map 在 2026/10/17 – 2026/11/15 这 30 天内被下载 3,496 次,日均约 117 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@getsoren/map 还在维护吗?

最新版本 1.11.2 发布于 2026/11/09(6 天前);至今共发布 8 个版本,其中过去 12 个月发布了 8 个;首次发布于 2026/05/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。