apidata.one docs Get a key

Map search

A map with pins, and a list of cards beside it, both following the same filters. This guide builds it with two calls: GET /v1/listings/map for the map and GET /v1/listings for the list.

The two calls

Both take the same filters. For the area on screen, send the map's corners as location.bbox:

GET /v1/listings/map?location.bbox=-75.42,40.00,-75.30,40.08&status=active&price.max=600000
GET /v1/listings?location.bbox=-75.42,40.00,-75.30,40.08&status=active&price.max=600000&limit=24

location.bbox is minLng,minLat,maxLng,maxLat: west, south, east, north.

The map call answers with pins, or with clusters when the area holds more than 500 listings:

{ "data": { "total": 3, "pins": [ { "listingKey": "805454359664", "lat": 40.01, "lng": -75.3, "price": 400000, "status": "active" } ], "clusters": [] } }
{ "data": { "total": 600, "pins": [], "clusters": [ { "lat": 40.4, "lng": -75.8, "count": 37, "bbox": [-75.81, 40.39, -75.79, 40.41] } ], "gridCellDegrees": 0.022 } }

The list call answers with listing objects, 24 a page, with meta.page.total and a nextCursor for the next page.

In the browser, with the publishable key

A map moves in the browser, so call from the browser with your publishable key (pk_…). It is made to be seen in a page: it works only from the website addresses on your account (and from localhost, for a test key), and by itself it can only read. Your secret key (sk_…) never goes into a page (authentication).

<div id="map" style="height: 480px"></div>
<ul id="cards"></ul>
<footer id="disclosures"></footer>
<script type="module">
  const API = 'https://api.apidata.one/v1';
  const headers = { Authorization: 'Bearer pk_test_…' }; // publishable: never the secret key
  const map = L.map('map').setView([40.02, -75.3], 12);
  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap contributors',
    maxZoom: 19,
  }).addTo(map);
  const marks = L.layerGroup().addTo(map);
  let running = null;
  let waiting = null;

  async function refresh() {
    running?.abort(); // the map moved again: the older answer is no longer wanted
    running = new AbortController();
    const b = map.getBounds();
    const box = [
      Math.max(b.getWest(), -180), Math.max(b.getSouth(), -90),
      Math.min(b.getEast(), 180), Math.min(b.getNorth(), 90),
    ].map((n) => n.toFixed(5)).join(',');
    const filters = new URLSearchParams({ 'location.bbox': box, status: 'active,coming_soon' });
    let mapAnswer;
    let listAnswer;
    try {
      [mapAnswer, listAnswer] = await Promise.all([
        fetch(`${API}/listings/map?${filters}`, { headers, signal: running.signal }),
        fetch(`${API}/listings?${filters}&limit=24`, { headers, signal: running.signal }),
      ]);
    } catch {
      return; // aborted, or offline
    }
    const refused = [mapAnswer, listAnswer].find((r) => r.status === 429);
    if (refused) {
      waiting = setTimeout(refresh, 1000 * Number(refused.headers.get('Retry-After') ?? 1));
      return;
    }
    if (!mapAnswer.ok || !listAnswer.ok) return showUnavailable();
    const { data } = await mapAnswer.json();
    const list = await listAnswer.json();
    marks.clearLayers();
    for (const pin of data.pins)
      L.marker([pin.lat, pin.lng])
        .bindTooltip(pin.price === null ? '' : `$${pin.price.toLocaleString('en-US')}`)
        .on('click', () => { location.href = `/listing/${encodeURIComponent(pin.listingKey)}`; })
        .addTo(marks);
    for (const c of data.clusters)
      L.circleMarker([c.lat, c.lng], { radius: 14 })
        .bindTooltip(String(c.count), { permanent: true, direction: 'center' })
        .on('click', () => map.fitBounds([[c.bbox[1], c.bbox[0]], [c.bbox[3], c.bbox[2]]]))
        .addTo(marks);
    showCards(list.data, list.meta.page);
    showDisclosures(list.compliance); // the texts every page with listings must show
  }

  map.on('moveend', () => {
    clearTimeout(waiting);
    waiting = setTimeout(refresh, 250); // one pair of calls when the map comes to rest
  });
  refresh();
</script>

showCards, showDisclosures and showUnavailable are yours. A card shows at least the listing office's name, photos use object-fit: contain, and the page shows the compliance texts (compliance).

Keep the calls few

A publishable key's requests share limits per key and per visitor address: 20 a second, with bursts of 50. A map can use that up quickly if every small movement calls the API.

Searching a town, a ZIP code or a county

Let the visitor type a name (autocomplete), then search the place by its ID and move the map to it:

GET /v1/places/pl_…                           → "bbox": [-75.35, 39.98, -75.25, 40.06]
GET /v1/listings/map?location.placeIds=pl_…
GET /v1/listings?location.placeIds=pl_…&limit=24

Filters combine with AND, so location.placeIds together with location.bbox finds the place's listings inside the area on screen.

Listings that are never on the map

A listing whose address is hidden has no point, so it is never a pin, never in a cluster and never found by location.bbox, a radius or a drawn shape (hidden addresses). It is found by a place, a city or a ZIP code. So for a search by place, the list can hold listings the map does not, and its total can be larger than the map's. Show those cards with their addressNotice in place of an address, and no "show on map" link.

Premium: outlines and drawn shapes

A key on a Basic account gets 403 tier_insufficient for these. Searching a place by its ID works on every tier.

Sorting by distance

sort=distance on the list needs a center: send location.radius.center=lng,lat and location.radius.meters. Like every spatial filter, it finds only listings with a shown address.

Map tiles

The example loads its map pictures from OpenStreetMap's own tile servers, which are free and meant for light use only. They are fine for building and for a demo. A site with real traffic needs a tile provider of its own (many offer OpenStreetMap-based tiles): change the tile address and its credit line, and nothing else.

On your server instead

The same two calls work from your server with the secret key, which is how a page is built for visitors without scripts and for search engines (an SEO-friendly site). Many sites do both: the first view built on the server, and the moving map in the browser.

This page as Markdown