vibes.diy Make an app → Discord
creator docs · reference · generated

Maps — a world overview, or a street map of places near the person

This is the same document the Vibes code generator reads when it builds apps — rendered from prompts/pkg/llms/maps.md on every deploy, so it can't drift from what the platform actually does. Read it from your terminal any time with npx vibes-diy skills.

The moment this is for: someone sees where, at a glance. A traveler's year lights up country by country, friends pick tonight's taco spot from the pins around them, a run club sees Saturday's route, a neighbor finds the nearest little free library. Both maps come with the platform, the outlines bundled and the street map drawn by the platform (Google's map on most pages, the free map elsewhere, with no key in the app's code), so the first screen opens full of real places.

Maps come in two shapes, and the ask picks one. Countries, travel journals, territory games and choropleths get the world overview below, drawn from bundled outlines. An ask about places someone can walk or drive to (restaurants, coffee, parks, "near me", "local", a city or zip, directions) gets the street map of places near the person further down: vector tiles, a place search, and a feed of real places that is full on the first screen.

World overview

For world maps, travel journals, country comparisons and territory games, import shapes and geometry from @vibes.diy/geo. The platform bundles the data and geometry together. Draw the outlines on the first render. Keep the person's reply about what they can see and do: “Your places now appear on the world map.”

Use the platform geometry module for world outlines. The package exports countries and land as GeoJSON FeatureCollections, plus geoNaturalEarth1, geoPath, geoContains, geoDistance and geoArea. Coordinates are always [longitude, latitude]. Each country has properties.name and usually a numeric ISO ID string, such as "250" for France. Preserve IDs as strings. A few disputed or unassigned areas lack IDs; use the name as the key fallback.

Fit the projection to the sphere so every result uses the same world frame. Use theme-token fills and strokes, a responsive viewBox, and a visible legend. Match the highlighted countries to the places the person requested. Offer an ordinary country/place button list alongside the map so small islands and keyboard users can select the same results. Country geometry is already oriented for D3; keep its rings intact.

jsximport React, { useState } from "react";
import { Button } from "@vibes.diy/ui";
import { countries, geoNaturalEarth1, geoPath } from "@vibes.diy/geo";

const projection = geoNaturalEarth1().fitExtent([[12, 12], [788, 408]], { type: "Sphere" });
const path = geoPath(projection);
// Connect these IDs to the app's real saved or computed results.
const matchingIds = new Set(["250", "392"]);

export default function App() {
  const [selected, setSelected] = useState(null);
  const matches = countries.features.filter(country => matchingIds.has(country.id));
  return <section className="space-y-4">
    <h2 className="text-xl font-semibold">Your places around the world</h2>
    <svg viewBox="0 0 800 420" className="w-full" role="img" aria-label="World map of matching countries">
      <path d={path({ type: "Sphere" })} className="fill-card stroke-border" />
      {countries.features.map(country => <path
        key={country.id || country.properties.name}
        d={path(country)}
        className={matchingIds.has(country.id) ? "fill-primary stroke-border cursor-pointer" : "fill-muted stroke-border"}
        onClick={matchingIds.has(country.id) ? () => setSelected(country.properties.name) : undefined}
      ><title>{country.properties.name}</title></path>)}
    </svg>
    <p className="text-sm"><span className="inline-block size-3 rounded-full bg-primary" /> Matching countries</p>
    <div className="flex flex-wrap gap-2">{matches.map(country =>
      <Button key={country.id} tone="info" variant="quiet"
        onClick={() => setSelected(country.properties.name)}>{country.properties.name}</Button>
    )}</div>
    <p aria-live="polite">{selected || "Choose a matching country to see its details."}</p>
    <p className="text-xs text-muted-foreground">Map data: Natural Earth</p>
  </section>;
}

For place markers, project the saved coordinates with projection([lng, lat]) and draw SVG circles at the resulting x/y. Give every marker a name and a corresponding accessible place button. A country can be found with countries.features.find(country => geoContains(country, [lng, lat])). At 1:110m resolution, small islands and coastal points may fall outside simplified polygons: retain the place marker and saved country association. A nearest-country or distance guess is not a reliable country assignment. Choropleths join to country IDs and display the units and range in their legend; missing data has its own fill and label.

World outlines come with the app; no runtime shape fetch is needed. The data is generalized Natural Earth 4.1.0 via world-atlas 2.0.2. It is made for world overviews; streets, neighborhoods and places to go are the street map's job.

Verify a world overview at phone width: outlines, matching fills and place markers appear, tapping a result opens its details, the legend is readable, and the outlines arrive with the app rather than from a shape download.

Street map of places near the person

A local ask opens on results. "Vegan restaurants I can share with friends", "coffee near me", "dog parks in my city": the first screen is a street map with numbered pins and a feed of real places beside it, with no form to fill first. The area comes from, in order: the area the person picked last time (kept in localStorage), a city-level guess from their connection (https://get.geojs.io/v1/ip/geo.json: city, region, latitude, longitude; no permission prompt), and a well-known city only when neither answers. Write all three steps in the app. A fixed starting city ("downtown San Francisco") is the last rung of that ladder, never the opening view, so the map opens wherever the person is.

A guess is city-level when it names a city. Some connections answer with only a country, and its coordinates are the middle of that country (37.751, -97.822 for the United States, a field in Kansas), so a guess counts only with its city and otherwise the ladder moves on to the well-known city:

jsconst FALLBACK = { label: "Portland, Oregon", lat: 45.523, lng: -122.676, how: "a starting city" };

export async function pickArea() {
  try {
    const kept = JSON.parse(localStorage.getItem("area") || "null");
    if (kept) return { ...kept, how: "the area you picked" };
  } catch {}
  try {
    const geo = await (await fetch("https://get.geojs.io/v1/ip/geo.json")).json();
    if (geo.city) {
      const label = [geo.city, geo.region].filter(Boolean).join(", ");
      return { label, lat: Number(geo.latitude), lng: Number(geo.longitude), how: "a guess from your connection" };
    }
  } catch {}
  return FALLBACK;
}

One line beside the results says what it shows and how the area was chosen: "18 spots within 5 mi of Portland, Oregon (a guess from your connection)".

That opening is for places the public world holds. When the ask is the person's own collection ("places I've been", "my favorite spots", "my trips"), the app opens on their own records and the place search is how they add the next one. A public list never stands in for their own.

The first paint reads well with no network. Above the map, the area line, the city or zip box and the location button render from code alone. The feed holds framed placeholders until the places arrive, and the map box shows a quiet background color until its tiles arrive. The platform keeps a shared answer for each area, so a return visit's search comes back quickly.

The location prompt runs only inside the handler of a button the person taps. A "Use my location" button calls navigator.geolocation.getCurrentPosition from its click handler, rounds to three decimals (a block, not a doorstep), and searches there. Never call it from an effect or at load: the guess already gave them a map, and the button is the upgrade they choose. A city or zip box sits beside it, looked up on submit with Photon (https://photon.komoot.io/api/?q=<text>&limit=5&lat=<lat>&lon=<lng>, biased toward the current area so "97214" finds Portland, not a village abroad). Reverse lookups for a friendly label use https://photon.komoot.io/reverse?lat=…&lon=….

Draw the map with Google's own loader, @googlemaps/js-api-loader. Write the Maps JavaScript API exactly as Google documents it: setOptions, then importLibrary("maps"), importLibrary("marker") and importLibrary("places"). The platform supplies the key and chooses how the map is drawn, so leave key out of setOptions (and apiKey out of a Loader) and keep the code the same everywhere. Most pages get Google mode: Google's own map, and places with star ratings, review counts and open-now. When Google is not available for a page, the same code draws the free map (OpenStreetMap), whose places carry rating: null and an unknown open-now, so write every card to read well in both. Give the map a container with a real height and theme the pins with the app's own classes:

jsximport React, { useEffect, useRef, useState } from "react";
import { setOptions, importLibrary } from "@googlemaps/js-api-loader";

setOptions({ v: "weekly" }); // the platform supplies the key

const FIELDS = ["id", "displayName", "location", "formattedAddress", "websiteURI", "regularOpeningHours", "primaryType", "rating", "userRatingCount"];

// One search. Google place types name what the person asked for.
export async function findPlaces({ center, radius, types }) {
  const { Place } = await importLibrary("places");
  const { places } = await Place.searchNearby({
    fields: FIELDS,
    locationRestriction: { center, radius },
    includedPrimaryTypes: types,
    maxResultCount: 20,
  });
  return places; // Place objects: place.displayName, place.location.lat(), place.location.toJSON()
}

export function PlaceMap({ places, center, selectedId, onPick }) {
  const box = useRef(null);
  const map = useRef(null);
  const pins = useRef(new Map());
  const [ready, setReady] = useState(false);
  useEffect(() => {
    let alive = true;
    importLibrary("maps").then(({ Map }) => {
      if (!alive) return;
      map.current = new Map(box.current, { center, zoom: 13, mapId: "places", gestureHandling: "cooperative" });
      setReady(true);
    });
    return () => { alive = false; };
  }, []);
  // Places arrive after the map: redraw whenever the list changes, once the map is ready.
  const ids = places.map((p) => p.id).join("|");
  useEffect(() => {
    if (!ready) return;
    let alive = true;
    Promise.all([importLibrary("marker"), importLibrary("core")]).then(([{ AdvancedMarkerElement }, { LatLngBounds }]) => {
      if (!alive) return;
      pins.current.forEach((pin) => { pin.map = null; });
      pins.current = new Map();
      const bounds = new LatLngBounds();
      places.forEach((place, i) => {
        const el = document.createElement("button");
        el.className = "grid size-8 place-items-center rounded-full border-2 border-background bg-primary text-xs font-bold text-primary-foreground shadow";
        el.textContent = String(i + 1); // the same number the feed shows
        el.setAttribute("aria-label", `${i + 1}. ${place.displayName}`);
        const pin = new AdvancedMarkerElement({ map: map.current, position: place.location, content: el, title: place.displayName });
        pin.addListener("click", () => onPick(place.id));
        pins.current.set(place.id, pin);
        bounds.extend(place.location);
      });
      if (places.length > 1) map.current.fitBounds(bounds, 48);
    });
    return () => { alive = false; };
  }, [ready, ids]);
  useEffect(() => {
    const pin = pins.current.get(selectedId);
    if (!pin) return;
    map.current.panTo(pin.position);
    if (map.current.getZoom() < 15) map.current.setZoom(15);
  }, [selectedId]);
  return <div className="h-80 overflow-hidden rounded-lg border border-border lg:h-screen">
    <div ref={box} className="h-full w-full" role="region" aria-label="Map of places" />
  </div>;
}

The platform sets the map's Map ID, so any mapId the app passes is fine. Google's Map has no destroy, so the effect's cleanup only stops a late callback: when the map's box leaves the page, the map lets go of itself. The map draws its own credit line, so the app adds none. Size the element you hand to new Map with h-full w-full inside a sized wrapper; an absolute inset-0 map box collapses to zero height. Once the person drags the map, offer a "Search this area" button that searches map.getCenter() with a radius taken from map.getBounds().

Stay within the supported subset of Google Maps, so the app also works on the free map: Map (center, zoom, mapId, fitBounds, panTo, setCenter, setZoom, getZoom, getCenter, getBounds, addListener), LatLng, LatLngBounds (extend, getCenter), marker.AdvancedMarkerElement (map, position, content, title, addListener("click")), marker.PinElement, InfoWindow (setContent, open({ map, anchor }), close), event.addListener / removeListener, and places.Place.searchNearby / Place.searchByText, and on each place isOpen(). Directions, geocoding, drawing, heat maps, Street View, Polyline/Polygon/Circle and place autocomplete are outside it: the Photon box is the area search, and directions open the phone's maps app (below).

Places come from Place.searchNearby, answered by the platform. Name what the person asked about with Google place types: vegan_restaurant, vegetarian_restaurant, restaurant, fast_food_restaurant, cafe, coffee_shop, bakery, ice_cream_shop, bar, park, dog_park, playground, museum, tourist_attraction, library, book_store, supermarket, grocery_store, pharmacy, gym. Place.searchByText (textQuery plus locationBias: { center, radius }) finds a place by name. Ask for every field the card shows in fields, since those are the ones that come back. A field a listing lacks reads null, so the card shows what is there: displayName, formattedAddress, websiteURI, regularOpeningHours.weekdayDescriptions as the hours lines, and rating with userRatingCount ("★ 4.6 (1,234)"). A listing's rating shows only when it is a number: Google mode's places carry one, the free map's read null, and the friends' own ratings sit beside it either way. Photos and reviews are not part of the answer. A search answers at most 20 places; start with a circle of about 8000 meters and widen it when fewer than 10 come back.

An "Open now" chip works in both modes. Ask place.isOpen() on the results rather than passing isOpenNow to the search: a Google place answers true or false, and a free-map place answers undefined, so it stays in the list with its hours lines. Count only the places that said true in the chip's label:

js// Keep what is open, and what cannot say (free-map places show their hours instead).
export async function openNow(places) {
  const open = await Promise.all(places.map((place) => place.isOpen()));
  return places.filter((_, i) => open[i] !== false);
}

While a search runs, the feed keeps its framed placeholders. A search that rejects carries a sentence: show "Try again" beside it, and a link that opens the same area on a directory that covers it (HappyCow for vegan food, the phone's maps app for anything else). Real places only: an empty area says so and suggests the nearest city or widening the circle. The person's own pins and notes are how a missing spot gets in, never invented names.

"Top" and "best" name their ranking in that one line: "fully vegan first, then friends' favorites, then the closest". Rank on what the answer holds: the place type that matches the ask most closely, the friends' own ratings, how complete the listing is (website, hours, address), and distance.

The person's layer sits on top of the places. Ratings, comments, saves and "been there" checks are the app's own records. Each one carries the spot's lat/lng and a snapshot of its name and address, plus the place id as a hint, so a note still reads well if the listing changes. A place card shows the notes within about 50 meters of the listing, and a note with no listing nearby shows as its own pin with its snapshot name:

js// Meters between two { lat, lng } points; close enough for "about 50 m".
const metersApart = (a, b) => {
  const dLat = (a.lat - b.lat) * 111320;
  const dLng = (a.lng - b.lng) * 111320 * Math.cos((a.lat * Math.PI) / 180);
  return Math.hypot(dLat, dLng);
};
const notesFor = (place, notes) => notes.filter((n) => metersApart(n, place.location.toJSON()) <= 50);

Every signed-in friend writes as themselves; pins the owner adds by hand join the feed with their own note.

The feed is the places, numbered like the pins. Saved spots and nearby places are one list, and that one list feeds both the pins and the feed: the spots the friends rated first, then every other place the search found, so the feed is full whenever the map has places. Hand the same array to PlaceMap and to the feed, and pin 3 is row 3:

jsx// One list: rated spots first, then the rest of the nearby places. Only notes inside the
// searched circle join, so the map frames this area; notes elsewhere feed the "saved spots
// around …" line. Notes within 50 m of each other are one spot: one pin, one row.
export function feedItems({ places, notes, center, radius }) {
  const here = notes.filter((n) => metersApart(n, center) <= radius);
  const listed = places.map((place) => {
    const at = place.location.toJSON();
    return { id: place.id, displayName: place.displayName, location: at, place, notes: here.filter((n) => metersApart(n, at) <= 50) };
  });
  const ownPins = [];
  for (const n of here) {
    if (listed.some((item) => metersApart(n, item.location) <= 50)) continue;
    const spot = ownPins.find((item) => metersApart(n, item.location) <= 50);
    if (spot) spot.notes.push(n);
    else ownPins.push({ id: n._id, displayName: n.name, location: { lat: n.lat, lng: n.lng }, place: null, notes: [n] });
  }
  return [...ownPins, ...listed.filter((item) => item.notes.length > 0), ...listed.filter((item) => item.notes.length === 0)];
}

export function Feed({ items, selectedId, onPick }) {
  return <Stack gap={2}>{items.map((item, i) => (
    <RowCard key={item.id} selected={item.id === selectedId} onClick={() => onPick(item.id)}>
      <Row gap={3}>
        <Badge tone="info">{i + 1}</Badge>
        <Stack gap={1}>
          <Text>{item.displayName}</Text>
          <Text size="sm" muted>{item.notes.length > 0 ? `${item.notes.length} ${item.notes.length === 1 ? "note" : "notes"} from friends` : item.place?.formattedAddress}</Text>
        </Stack>
      </Row>
    </RowCard>
  ))}</Stack>;
}

// const items = feedItems({ places, notes, center, radius }); // the same center and radius as findPlaces
// <PlaceMap places={items} center={center} selectedId={selectedId} onPick={setSelectedId} />
// <Feed items={items} selectedId={selectedId} onPick={setSelectedId} />

Example spots sit where the map opens with no guess. seed.json places its example ratings and notes around the app's well-known city, at the same coordinates as FALLBACK, each on a real, well-known place there with its name and address. When the person's area holds none of their saved spots and they have some elsewhere, the line under the feed names where they are and moves the map there on a tap: "7 saved spots around Portland, Oregon". Every visitor sees the nearby places in the feed, and the friends' spots are one tap away.

Directions open the phone's maps app: https://www.google.com/maps/dir/?api=1&destination=<lat>,<lng>&travelmode=driving, or https://maps.apple.com/?daddr=<lat>,<lng>&dirflg=d on Apple devices. A place shares as the app's public address with #place=<id>&at=<lat>,<lng> in the fragment. A friend opening it lands on that area with the place open.

Verify the first preview at phone width. The map paints, the numbered pins match the feed, the feed lists the nearby places, and tapping a pin brings its card into view. The location prompt appears only after "Use my location". A typed zip moves the map, and the map shows its credit line.