Back to Blog
Guide

Facebook Marketplace Search: How to Filter Results by Real Distance

November 18, 2026
17 min read
S
By SociaVault Team
Facebook MarketplaceradiusdistancegeocodingJavaScriptPython

A customer sent us a Marketplace search that looked simple: a keyword, their city's coordinates and radius_km=100. Plenty of the listings that came back were much farther away than 100 km. Some were in other states, and many of the far ones were local pickup only.

Our API passes radius_km to Marketplace unchanged and returns the listings as Marketplace sends them, so any distance filtering has to happen in your code. We wanted to know how often listings land outside the radius. On 1 November 2026 we ran the searches ourselves and measured every result. In our tests, 23% of results were beyond the radius we asked for. Changing the sort order or the delivery filter didn't remove all of them. Computing each listing's distance ourselves did, and the code for that is below.

What we measured

We ran six searches around Austin, Texas and Denver, Colorado, with a specific query (herman miller aeron) and a broad one (couch). Austin got both queries at 40 km and 100 km, and Denver got both at 100 km. Everything else stayed at its default. For each listing we looked up its city with the location-search endpoint and measured the straight-line distance from the search point.

QueryAroundradius_kmResultsBeyond the radiusShareFarthest
herman miller aeronAustin4013646%236 km
herman miller aeronAustin10016956%2,812 km
herman miller aeronDenver10015320%1,408 km
couchAustin4024417%2,344 km
couchAustin1001500%29 km
couchDenver1001400%42 km
All six972223%

The six searches returned 97 results, or 88 different listings, since a few showed up in more than one search. Of those 97, 22 were beyond the radius.

The query mattered more than the radius. The Aeron searches had 18 of 44 results beyond the radius (41%), against 4 of 53 (8%) for the couch searches. Couch searches found plenty of local matches. The Aeron searches found fewer, and more of what they returned was far away.

The 100 km Aeron search around Austin looks a lot like what the customer described. Five of its 16 results were in other states: New York, Wisconsin, Maine, California and North Carolina, between 1,666 and 2,812 km away. Four more were in Texas but past 100 km: two around San Antonio (about 120 km), one in Houston (236 km) and one in Texas City (291 km).

A bigger radius didn't bring more stray results, either. The Austin couch search at 40 km had four results beyond 40 km, one of them in California. The same search at 100 km had none, and its farthest listing was 29 km out.

Which listings land outside the radius

Delivery type lined up with distance almost perfectly. Every listing carries a delivery_types list, and across the 97 results we saw six values:

ValueResults
IN_PERSON94
DOOR_PICKUP22
PUBLIC_MEETUP6
SHIPPING_ONSITE5
SHIPPING_OFFSITE3
DOOR_DROPOFF3

Eight results had one of the two shipping values. We'll call the rest "in-person only", because every delivery option they list involves meeting up, picking up or dropping off. Here's how the two groups split by distance:

Distance from the search pointResultsOffer shippingIn-person only
Within the radius75075
Beyond the radius, under 300 km15114
300 km or more770

The seven results more than 300 km away were all out of state, and every one offered shipping. Three came from Citrus Heights, California. The same Aeron armrest turned up in the 100 km Aeron searches around both Austin and Denver, and a couch cushion support showed up in the Austin couch search at 40 km. All three were listed with SHIPPING_OFFSITE and nothing else. If your users can take delivery, results like these may be worth keeping.

The middle row is the customer's problem. Fourteen of the 15 results that were past the radius but under 300 km were in-person only. All 14 were in the same state as the search: San Antonio and Houston in the Austin searches, Colorado Springs in the Denver one, and towns such as Georgetown (43 km), Jarrell (63 km) and Killeen (93 km) in the 40 km searches. An Aeron in Houston that can only be collected in person is 236 km from Austin in a straight line, and farther by road.

Two search settings we tried first

The search endpoint has two parameters that look like they should help, so we tried both on the worst case, the Austin Aeron search at 100 km.

sort_by=distance_ascend returned 24 results. The first six were the ones beyond the radius, in this order: 236, 291, 2,432, 1,897, 1,666 and 2,812 km. All six offered shipping, and the 18 Austin results came after them. The mix of listings changed too. Only 2 of the 24 titles mentioned Aeron, against 11 of 16 with the default sort, and most of the rest were desks and other office chairs. In this test, the order wasn't something you could cut off at your radius.

delivery_method=local_pickup returned 14 results, none offering shipping and none out of state. The far in-person listings stayed, though. Five of the 14 (36%) were still beyond 100 km: three in Houston and two around San Antonio.

Both settings are worth knowing about. Neither one kept every result inside the radius in our tests.

How to get a distance for every listing

Search results don't include coordinates. Each listing has a location object instead. This one is from the Austin search:

{
  "city": "San Antonio",
  "state": "TX",
  "display_name": "Helotes, Texas",
  "city_page_id": "112926008717496"
}

To turn that into a point on a map, look the place up with location-search. Three things tripped us up on the way:

  • The abbreviated state returns nothing. query=Austin, TX came back with an empty locations object, while query=Austin, Texas works. Search results give you state as TX but spell the state out in display_name, so query with display_name.
  • The first result isn't always the city. query=Austin returned 10 places, and the first one was the Austin neighborhood in Chicago. Code that takes locations[0] would have put every Austin listing in Illinois.
  • city and display_name sometimes disagree. They named different places in 10 of the 97 results. One listing said San Antonio in city and Helotes in display_name. Others paired Aurora with Denver, or Austin with Round Rock.

The fix for all three: query location-search with the listing's display_name, then take the result whose page_id equals the listing's city_page_id. All 31 cities in our data matched that way, so there's no guessing between Austin, Texas and Austin, Minnesota.

Cache the result under city_page_id, so each city costs one call. Our 97 results came from 31 cities, which meant 31 lookups instead of 97. Saved to disk, the cache keeps paying off. When we reran the Aeron search to test the code below, each run turned up just one city it hadn't seen before.

The distance itself is the great-circle (haversine) distance between your search point and the city's point. If these endpoints are new to you, how to scrape Facebook Marketplace with Python covers the basics, and the docs list every parameter for search, location search and item.

The filter in JavaScript

This runs one page of search results, looks up any city it hasn't seen before, and sorts each listing into one of three lists. nearby is within the radius. shipsToYou is farther away but offers shipping, and only fills up if you pass includeShipping: true. Everything else goes to dropped, including listings whose city couldn't be matched, so nothing slips through with an unknown distance. In our responses, listings, locations and delivery_types all came back as objects with numbered keys rather than arrays, which is why the code runs every list through asList. Save it as an .mjs file and run it with Node 18 or later:

import { readFile, writeFile } from "node:fs/promises";

const API = "https://api.sociavault.com/v1/scrape/facebook-marketplace";
const HEADERS = { "x-api-key": process.env.SOCIAVAULT_API_KEY };
const CACHE_FILE = "marketplace-cities.json";

// Lists can come back as arrays or as objects with numbered keys
const asList = (x) => (Array.isArray(x) ? x : Object.values(x ?? {}));
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function get(path, params) {
  const res = await fetch(`${API}/${path}?${new URLSearchParams(params)}`, {
    headers: HEADERS,
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
  return (await res.json()).data ?? {};
}

// Great-circle distance in km
function distanceKm(lat1, lng1, lat2, lng2) {
  const rad = (d) => (d * Math.PI) / 180;
  const a =
    Math.sin(rad(lat2 - lat1) / 2) ** 2 +
    Math.cos(rad(lat1)) *
      Math.cos(rad(lat2)) *
      Math.sin(rad(lng2 - lng1) / 2) ** 2;
  return 2 * 6371 * Math.asin(Math.sqrt(a));
}

// One location-search call per city, cached by the listing's city_page_id
async function cityPoint(loc, cache) {
  const id = loc?.city_page_id;
  if (!id || !loc.display_name) return null;
  if (!(id in cache)) {
    const data = await get("location-search", { query: loc.display_name });
    const hits = asList(data.locations);
    const hit =
      hits.find((h) => h.page_id === id) ??
      hits.find((h) => h.name === loc.display_name);
    cache[id] = hit
      ? { name: hit.name, lat: hit.latitude, lng: hit.longitude }
      : null;
    await sleep(300);
  }
  return cache[id];
}

const ships = (types) => types.some((t) => String(t).startsWith("SHIPPING"));

async function searchNearby({
  query,
  lat,
  lng,
  radiusKm,
  includeShipping = false,
  maxPages = 1,
}) {
  let cache = {};
  try {
    cache = JSON.parse(await readFile(CACHE_FILE, "utf8"));
  } catch {}
  const nearby = [],
    shipsToYou = [],
    dropped = [];
  let cursor;
  for (let page = 0; page < maxPages; page++) {
    const params = { query, lat, lng, radius_km: radiusKm };
    if (cursor) params.cursor = cursor;
    const data = await get("search", params);
    for (const item of asList(data.listings)) {
      const point = await cityPoint(item.location, cache);
      const d = point ? distanceKm(lat, lng, point.lat, point.lng) : null;
      const delivery = asList(item.delivery_types);
      const row = {
        id: item.id,
        title: item.title,
        price: item.price?.amount,
        city: item.location?.display_name,
        km: d === null ? null : Math.round(d),
        delivery,
      };
      if (d !== null && d <= radiusKm) nearby.push(row);
      else if (includeShipping && ships(delivery)) shipsToYou.push(row);
      else dropped.push(row);
    }
    cursor = data.cursor;
    if (!data.has_next_page || !cursor) break;
    await sleep(500);
  }
  await writeFile(CACHE_FILE, JSON.stringify(cache, null, 2));
  return { nearby, shipsToYou, dropped };
}

const { nearby, shipsToYou, dropped } = await searchNearby({
  query: "herman miller aeron",
  lat: 30.2677, // Austin, Texas, from location-search
  lng: -97.7475,
  radiusKm: 100,
  includeShipping: true,
});
console.log(
  `within 100 km: ${nearby.length}, farther but ships: ${shipsToYou.length}, dropped: ${dropped.length}`,
);
for (const r of dropped)
  console.log(
    `  dropped: ${r.km ?? "?"} km, ${r.city}, ${r.delivery.join("+")}, ${r.title}`,
  );

Our run on 1 November 2026 printed this:

within 100 km: 9, farther but ships: 0, dropped: 5
  dropped: 120 km, Helotes, Texas, IN_PERSON, Herman Miller Aeron Classic
  dropped: 119 km, San Antonio, Texas, IN_PERSON, Herman Miller Aeron (Titanium) 50+ IN STOCK
  dropped: 236 km, Houston, Texas, IN_PERSON, Múltiples Herman Miller Aeron chairs size B and C
  dropped: 236 km, Houston, Texas, IN_PERSON, Sills Herman Miller Aeron Stool  para oficina o dibujo
  dropped: 236 km, Houston, Texas, IN_PERSON, Herman Miller Aeron Chair

Each page costs 1 credit. If the filter throws out half a page, raise maxPages to fill your list, and keep a cap so a loop can't run on forever.

The same filter in Python

The Python version reads and writes the same cache file, so the two can share city lookups:

import json
import math
import os
import time

import requests

API = "https://api.sociavault.com/v1/scrape/facebook-marketplace"
HEADERS = {"x-api-key": os.environ["SOCIAVAULT_API_KEY"]}
CACHE_FILE = "marketplace-cities.json"


def as_list(x):
    # Lists can come back as lists or as dicts with numbered keys
    return list(x.values()) if isinstance(x, dict) else (x or [])


def get(path, params):
    r = requests.get(f"{API}/{path}", params=params, headers=HEADERS, timeout=60)
    r.raise_for_status()
    return r.json().get("data") or {}


def distance_km(lat1, lng1, lat2, lng2):
    # Great-circle distance in km
    p1, p2 = math.radians(lat1), math.radians(lat2)
    a = (math.sin((p2 - p1) / 2) ** 2
         + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lng2 - lng1) / 2) ** 2)
    return 2 * 6371 * math.asin(math.sqrt(a))


def city_point(loc, cache):
    # One location-search call per city, cached by the listing's city_page_id
    loc = loc or {}
    pid, name = loc.get("city_page_id"), loc.get("display_name")
    if not pid or not name:
        return None
    if pid not in cache:
        hits = as_list(get("location-search", {"query": name}).get("locations"))
        hit = (next((h for h in hits if h.get("page_id") == pid), None)
               or next((h for h in hits if h.get("name") == name), None))
        cache[pid] = ({"name": hit["name"], "lat": hit["latitude"], "lng": hit["longitude"]}
                      if hit else None)
        time.sleep(0.3)
    return cache[pid]


def ships(types):
    return any(str(t).startswith("SHIPPING") for t in types)


def search_nearby(query, lat, lng, radius_km, include_shipping=False, max_pages=1):
    try:
        with open(CACHE_FILE) as f:
            cache = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        cache = {}
    nearby, ships_to_you, dropped = [], [], []
    cursor = None
    for _ in range(max_pages):
        params = {"query": query, "lat": lat, "lng": lng, "radius_km": radius_km}
        if cursor:
            params["cursor"] = cursor
        data = get("search", params)
        for item in as_list(data.get("listings")):
            point = city_point(item.get("location"), cache)
            d = distance_km(lat, lng, point["lat"], point["lng"]) if point else None
            delivery = as_list(item.get("delivery_types"))
            row = {
                "id": item.get("id"),
                "title": item.get("title"),
                "price": (item.get("price") or {}).get("amount"),
                "city": (item.get("location") or {}).get("display_name"),
                "km": None if d is None else round(d),
                "delivery": delivery,
            }
            if d is not None and d <= radius_km:
                nearby.append(row)
            elif include_shipping and ships(delivery):
                ships_to_you.append(row)
            else:
                dropped.append(row)
        cursor = data.get("cursor")
        if not data.get("has_next_page") or not cursor:
            break
        time.sleep(0.5)
    with open(CACHE_FILE, "w") as f:
        json.dump(cache, f, indent=2)
    return nearby, ships_to_you, dropped


nearby, ships_to_you, dropped = search_nearby(
    "herman miller aeron", 30.2677, -97.7475,  # Austin, Texas, from location-search
    radius_km=100, include_shipping=True)
print(f"within 100 km: {len(nearby)}, farther but ships: {len(ships_to_you)}, dropped: {len(dropped)}")
for r in dropped:
    print(f"  dropped: {r['km']} km, {r['city']}, {'+'.join(r['delivery'])}, {r['title']}")

We ran it two minutes after the JavaScript version:

within 100 km: 9, farther but ships: 7, dropped: 5
  dropped: 120 km, Helotes, Texas, IN_PERSON, Herman Miller Aeron Classic
  dropped: 119 km, San Antonio, Texas, IN_PERSON, Herman Miller Aeron (Titanium) 50+ IN STOCK
  dropped: 236 km, Houston, Texas, IN_PERSON, Múltiples Herman Miller Aeron chairs size B and C
  dropped: 236 km, Houston, Texas, IN_PERSON, Sills Herman Miller Aeron Stool  para oficina o dibujo
  dropped: 236 km, Houston, Texas, IN_PERSON, Herman Miller Aeron Chair

The same five listings were dropped. This time the search also returned seven far-away listings that offer shipping, and include_shipping=True kept them in a separate list instead of mixing them in with the local ones. Leave it at the default False if your users can only collect in person.

This matters most for anything that summarizes a local market. A Marketplace price tracker or a city-by-city product research script will count listings from other cities as local unless you drop them first.

When a city isn't precise enough

A city-level distance treats every listing as if it sits at the city's center point. That's plenty for a listing in Houston, 236 km from Austin. Near your radius line, the center point can put a listing on the wrong side.

The item endpoint returns the listing's own coordinates at data.location.latitude and data.location.longitude, for 1 credit per listing. We checked two:

  • A couch near Austin, with city set to Austin and display_name set to Round Rock, Texas. Its item coordinates were 23 km from the search point. Round Rock's center point is 28 km out, and Austin's center is the search point itself. So the distance from display_name was 5 km off, and the one from city would have been 23 km off.
  • An Aeron in Colorado Springs, from the Denver search at 100 km. The city level said 102 km and the item said 102.2 km. It was still outside, by about two kilometers.

You don't need item coordinates for every listing. Use city-level distances first, then look up items only for listings close to the line. In our six searches, 10 of the 97 results were within 15 km of their radius, so checking those would have cost 10 credits instead of 97.

Honest limits

  • City-level distances are approximate. A metro area can easily span 50 km, and a city's center point says nothing about which side of town a listing is on. The item endpoint gives a listing's own coordinates, but at 1 credit per listing.
  • These are straight-line distances. Driving distance is longer, sometimes a lot longer.
  • Results change between calls. The same Aeron search returned 16, 14 and 21 listings on three calls within 17 minutes. Our percentages describe these 97 results, not Marketplace as a whole.
  • The sample is small. We ran six searches in two US cities on one day. Rural areas, rarer items and other countries could look very different.
  • Filtering costs you results. Drop half a page and you'll need more pages to fill a list, at 1 credit each plus any new cities.
  • Empty lookups still count. A location-search query that matches nothing is still a successful call, so a badly formatted city name costs a credit each time you try it. The code caches misses as well as hits for that reason.
  • We can only describe what came back. We don't know how Marketplace chooses which listings to include, and we haven't tried to guess.

Frequently Asked Questions

Why does Facebook Marketplace show listings outside my search radius?

We don't know how Marketplace picks its results. What we can describe is what came back: in six searches on 1 November 2026, 23% of results were beyond the radius we set. Results more than 300 km away all offered shipping, and most of the rest were in-person listings from other cities in the same state.

Can I sort Marketplace search results by distance?

The search endpoint accepts sort_by=distance_ascend, but in our test the first six of 24 results were the farthest ones, 236 to 2,812 km away, with the local listings after them. Compute the distances yourself and sort on your side.

Does the local pickup filter remove far-away listings?

delivery_method=local_pickup returned no listings that offered shipping, so the out-of-state results were gone. In-person listings beyond the radius stayed. In our Austin test, 5 of 14 results were 119 to 236 km away.

How do I get the exact location of a Marketplace listing?

Call /v1/scrape/facebook-marketplace/item with the listing's id. The listing's own coordinates are at data.location.latitude and data.location.longitude, which beats a city's center point when a listing is near your radius. It costs 1 credit per listing, so save it for those.

How accurate is a distance based on the listing's city?

It's good enough for most listings and least reliable near your radius line. In one Austin check, the estimate from display_name was 5 km off. The city field would have been 23 km off for the same listing, which is why we geocode display_name.

How many credits does distance filtering cost?

One credit per search page, plus one for each city you haven't looked up before. Our six searches needed 31 city lookups. With the cache saved, each later run of the same search found one new city.


Want to check your own searches? Sign up for 50 free credits, no card needed, and run the filter on the radius your users actually care about.

Found this helpful?

Share it with others who might benefit

Ready to Try SociaVault?

Start extracting social media data with our powerful API. No credit card required.