English

Poradnik · Google Maps

Pinezki na mapie Google – markery, klastry, okna informacyjne

Praktyczny przewodnik po pinezkach w Google Maps i React – warianty Pin dla statusów, własne znaczniki HTML, okna informacyjne, klastry z własnym wyglądem, poziomy szczegółowości, synchronizacja listy z widokiem mapy i wydajność przy 1500 punktach.

Autor · · 21 min czytania

Pinezka to najczęściej używany element mapy i jednocześnie miejsce, w którym aplikacje najszybciej robią się wolne i nieczytelne. W tym artykule budujesz mapę 1500 paczkomatów, w których klienci pierogarni odbierają zamówienia, i przechodzisz przez wszystkie decyzje: jak pokazać status punktu, kiedy zwykła pinezka, a kiedy własny znacznik HTML, jak zgrupować punkty w klastry i jak zsynchronizować listę z tym, co widać na mapie.

Wymagania wstępne: podstawy @vis.gl/react-google-maps (APIProvider, Map, AdvancedMarker) z poradnika Google Maps w React, React z hookami i TypeScript.

1500
punktów na mapie – 8 miast, 3 statusy
9
elementów DOM w widoku Polski – 8 klastrów + 1 podświetlenie
15
próg zoomu – od tego poziomu znaczniki HTML zamiast klastrów
1
tabela stylów statusu – pinezki, znaczniki i lista mówią tym samym kolorem

Trzy rodzaje znaczników

RodzajKiedyW tym projekcie
AdvancedMarker + Pinklasyczna pinezka z kolorem, obramowaniem, znakiem i skaląpunkty w klastrach, podświetlenie najechania i wyboru
AdvancedMarker z dzieckiem HTMLtreść niemieszcząca się w pinezce: cena, liczba, zdjęcie, etykietapigułka „24 free” przy zbliżeniu
znacznik klastra (renderer)grupa punktów jako jeden znacznikbańka z liczbą punktów

Starsza klasa google.maps.Marker jest przestarzała od lutego 2024. Wszystkie trzy rodzaje opierają się na AdvancedMarkerElement, który wymaga Map ID.

Krok 1. Projekt i dane

Konfiguracja, style i punkt wejścia

package.json
{
  "name": "pierogi-lockers-map",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@googlemaps/markerclusterer": "^2.6.2",
    "@vis.gl/react-google-maps": "^1.10.2",
    "react": "^19.3.1",
    "react-dom": "^19.3.1"
  },
  "devDependencies": {
    "@types/google.maps": "^3.67.0",
    "@types/react": "^19.3.0",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client", "google.maps"],
    "jsx": "react-jsx",
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true
  },
  "include": ["src", "vite.config.ts"]
}
vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [react()],
});
.env.example
# Copy to .env.local. Restrict the key to your domains (HTTP referrers) and to Maps JavaScript API.
VITE_GOOGLE_MAPS_API_KEY=your-browser-key
VITE_GOOGLE_MAPS_MAP_ID=DEMO_MAP_ID
src/env.d.ts
interface ImportMetaEnv {
  readonly VITE_GOOGLE_MAPS_API_KEY?: string;
  readonly VITE_GOOGLE_MAPS_MAP_ID?: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogarnia · Pick-up lockers</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
src/index.css
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; color: #1f2328; }
.layout { display: grid; grid-template-columns: 360px 1fr; height: 100dvh; }
.sidebar { display: grid; grid-template-rows: auto auto auto 1fr; gap: 12px; padding: 16px; border-right: 1px solid #dee2e6; min-height: 0; }
.filters { display: flex; flex-wrap: wrap; gap: 6px; }
.filters label { display: inline-flex; gap: 6px; align-items: center; padding: 4px 10px; border: 1px solid #dee2e6; border-radius: 999px; cursor: pointer; }
.list { list-style: none; margin: 0; padding: 0; overflow-y: auto; display: grid; gap: 6px; align-content: start; }
.list button { width: 100%; display: flex; justify-content: space-between; gap: 8px; padding: 8px 10px; border: 1px solid #dee2e6; border-radius: 8px; background: #fff; text-align: left; font: inherit; cursor: pointer; }
.list button[aria-current="true"] { border-color: #c2255c; background: #fff0f6; }
.muted { color: #6c757d; font-size: 0.875rem; }
.btn { padding: 6px 12px; white-space: nowrap; border-radius: 8px; border: 1px solid #c2255c; background: #fff; color: #c2255c; font: inherit; cursor: pointer; }
.btn-primary { background: #c2255c; color: #fff; }
/* Cluster bubble created by the custom renderer */
.cluster { display: grid; place-items: center; border-radius: 50%; background: #c2255c; color: #fff; font: 600 13px system-ui, sans-serif; border: 3px solid rgba(255, 255, 255, 0.9); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); cursor: pointer; }
/* Rich HTML marker shown at street level */
.slot-badge { position: relative; padding: 3px 8px; border-radius: 999px; background: #fff; border: 2px solid currentColor; font: 600 12px system-ui, sans-serif; white-space: nowrap; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.25); transition: transform 120ms ease-out; }
.slot-badge::after { content: ""; position: absolute; left: 50%; bottom: -7px; translate: -50% 0; border: 5px solid transparent; border-top-color: currentColor; }
.slot-badge[data-active="true"] { transform: scale(1.15); background: currentColor; }
.slot-badge[data-active="true"] span { color: #fff; }
@media (prefers-reduced-motion: reduce) { .slot-badge { transition: none; } }
@media (max-width: 760px) { .layout { grid-template-columns: 1fr; grid-template-rows: 45dvh 1fr; } }
src/main.tsx
import { APIProvider } from "@vis.gl/react-google-maps";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";

const container = document.getElementById("root");
if (!container) throw new Error("#root element not found");

createRoot(container).render(
  <StrictMode>
    <APIProvider apiKey={import.meta.env.VITE_GOOGLE_MAPS_API_KEY ?? ""} language="pl" region="PL">
      <App />
    </APIProvider>
  </StrictMode>,
);

Dane to 1500 punktów z identyfikatorem, miastem, współrzędnymi i liczbą wolnych skrytek. Status wyliczamy z liczby skrytek, więc nie da się zapisać sprzecznego stanu typu „pełny z 12 wolnymi miejscami”. Pomocnicze funkcje geometryczne działają na literałach LatLngBoundsLiteral i nie potrzebują załadowanego API map.

Dane i geometria

src/data/lockers.ts
export type LockerStatus = "available" | "busy" | "full";

export interface Locker {
  id: string;
  city: string;
  position: google.maps.LatLngLiteral;
  freeSlots: number;
  status: LockerStatus;
}

const cities = [
  { code: "WAW", name: "Warszawa", lat: 52.2297, lng: 21.0122, count: 380 },
  { code: "KRK", name: "Kraków", lat: 50.0647, lng: 19.945, count: 230 },
  { code: "WRO", name: "Wrocław", lat: 51.1079, lng: 17.0385, count: 200 },
  { code: "GDA", name: "Gdańsk", lat: 54.372, lng: 18.638, count: 180 },
  { code: "POZ", name: "Poznań", lat: 52.4064, lng: 16.9252, count: 160 },
  { code: "LDZ", name: "Łódź", lat: 51.7592, lng: 19.456, count: 140 },
  { code: "KAT", name: "Katowice", lat: 50.2649, lng: 19.0238, count: 120 },
  { code: "LUB", name: "Lublin", lat: 51.2465, lng: 22.5684, count: 90 },
];

// Deterministic pseudo-random generator + Box–Muller for a city-like (dense centre) spread.
let seed = 2026;
const rand = () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646;
const gauss = () => Math.sqrt(-2 * Math.log(rand() + 1e-9)) * Math.cos(2 * Math.PI * rand());

export const statusOf = (freeSlots: number): LockerStatus => (freeSlots === 0 ? "full" : freeSlots < 5 ? "busy" : "available");

// 1 500 lockers – in a real app: GET /api/lockers returning id, lat, lng, freeSlots only.
export const lockers: Locker[] = cities.flatMap((city) =>
  Array.from({ length: city.count }, (_, i) => {
    const freeSlots = Math.max(0, Math.round(rand() * 26) - 2);
    return {
      id: `${city.code}-${String(i + 1).padStart(4, "0")}`,
      city: city.name,
      position: { lat: city.lat + gauss() * 0.045, lng: city.lng + gauss() * 0.07 },
      freeSlots,
      status: statusOf(freeSlots),
    };
  }),
);
src/lib/geo.ts
export function inBounds(p: google.maps.LatLngLiteral, b: google.maps.LatLngBoundsLiteral): boolean {
  return p.lat <= b.north && p.lat >= b.south && p.lng <= b.east && p.lng >= b.west;
}

// Grow the bounds a little, so markers just outside the edge are ready before the user pans.
export function padBounds(b: google.maps.LatLngBoundsLiteral, ratio = 0.2): google.maps.LatLngBoundsLiteral {
  const dLat = (b.north - b.south) * ratio;
  const dLng = (b.east - b.west) * ratio;
  return { north: b.north + dLat, south: b.south - dLat, east: b.east + dLng, west: b.west - dLng };
}

export function boundsOf(points: google.maps.LatLngLiteral[]): google.maps.LatLngBoundsLiteral | null {
  if (points.length === 0) return null;
  let north = -90, south = 90, east = -180, west = 180;
  for (const p of points) {
    north = Math.max(north, p.lat);
    south = Math.min(south, p.lat);
    east = Math.max(east, p.lng);
    west = Math.min(west, p.lng);
  }
  return { north, south, east, west };
}

W prawdziwej aplikacji API powinno zwracać tylko to, co potrzebne do narysowania punktu (id, współrzędne, status). Opis, godziny otwarcia i zdjęcia pobieraj dopiero po kliknięciu. Przy 1500 punktach różnica między 60 kB a 1,5 MB JSON-a jest odczuwalna na telefonie.

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Krok 2. Pinezki i własne znaczniki HTML
  • Krok 3. Klastry z własnym wyglądem
  • Krok 4. Okno informacyjne
  • Krok 5. Składamy aplikację: poziomy szczegółowości i lista z widoku
  • Wydajność: co dał każdy krok
  • Typowe błędy
  • Sprawdź się
  • Co dalej

Załóż darmowe konto · Zaloguj się