How to Build a Local Business Lead List from Google Maps
Michael Carter · · 22 min read

Key takeaways
- A grid of 3 categories in 3 US cities, searched on BestSERP's /maps endpoint with pages: 2 on November 17, 2026, returned 180 listings for 18 credits, each with coordinates, a ChIJ place ID and a CID.
- De-duplicate on the CID, not the name: one studio appeared twice in the same query under two spellings of its address, while 7 chain names covered 21 different locations.
- Check coordinates on every run: a city bounding box from the US Census Bureau rejected none of our 179 leads but flags the 3 Manhattan pharmacies an earlier "pharmacy in Austin" search returned.
- The results contain no website, phone number or email address: link was a Google Maps URL in 180 of 180 listings, so contact details come from your own process or Google's Places API.
- The listings cost about $0.05 per 1,000 leads; the FTC's CAN-SPAM guide says the law makes no exception for business-to-business email, so opt-outs and a postal address are required.
A local business lead list is a table of businesses in the categories and cities you sell to. You can build one from Google Maps results: search each category in each city, de-duplicate on Google's CID, check each listing's coordinates against the city, then export a CSV. Our grid of 9 searches yielded 179 leads for 18 credits.
This tutorial is for developers and growth teams who sell to local businesses. It walks through a runnable Python project on BestSERP (bestserp.com), a Google SERP API: a grid of 3 categories in 3 US cities, duplicate and location checks, a CSV export, the cost per 1,000 leads, the email rules that apply, and what the results do not contain. For the wider picture, see our developer's guide to local search data.
What you will build
You will build a Python program that turns categories and cities into a de-duplicated CSV of businesses, each checked against the city you searched, in five stages:
- Grid: each category in each city becomes one query, such as "yoga studio in Austin, TX".
- Search: one request per query to the Google Maps endpoint, with
pages: 2for 20 listings. Raw responses are saved, so a re-run is free. - De-duplicate: one row per CID.
- Check location: listings outside the city's bounding box go to a separate file.
- Export:
leads.csvfor Excel or Google Sheets,outside.csvfor review.

Each CSV row is one business: name, category, street address, city, rating, review count, coordinates, CID, place ID, Maps URL, the queries that found it and the search time.
Prerequisites
- Python 3 and requests. We used Python 3.12.10 and requests 2.34.2.
- A BestSERP API key. Create a free account for 3,000 free searches, valid for 30 days, and keep the key in an environment variable. The quickstart shows the first request in five languages.
- About 20 credits for the grid in this tutorial (1 credit per page of results).
pip install requests
export BESTSERP_API_KEY="YOUR_API_KEY" # PowerShell: $env:BESTSERP_API_KEY = "YOUR_API_KEY"
Plan the query grid
A query grid is every business category you sell to combined with every city you cover, written as plain text. BestSERP targets results by country (gl) and language (hl) only (how the gl and hl parameters work); a location parameter is refused before it costs anything, so the city goes in the query.
Our example sells to fitness studios. Listings returned per query with pages: 2:
| Category | Austin, TX | Denver, CO | Columbus, OH |
|---|---|---|---|
| yoga studio | 20 | 20 | 20 |
| pilates studio | 20 | 20 | 20 |
| gym | 20 | 20 | 20 |
Four rules make a grid work:
- Add the state. Austin and Columbus each exist in more than one state; "Columbus, OH" leaves no doubt.
- Reuse Google's category names. Each listing carries a
category, such as "Yoga studio". Run one page first and copy the wording. - Choose the depth.
/mapsreturns 10 listings per page, up to 5 pages per request, 1 credit each. A grid costs categories x cities x pages credits: 3 x 3 x 2 = 18 here. - Use
/maps, not/places. Places returns 20 listings per credit but no coordinates or CID (Google Places vs Google Maps results compares them), and coordinates make the location check possible.
Get each city's bounding box
A bounding box is the smallest rectangle around a city's legal boundary. The US Census Bureau's TIGERweb serves the boundary of every incorporated place, free and without a key:
import json
import requests
LAYER = ("https://tigerweb.geo.census.gov/arcgis/rest/services/"
"TIGERweb/Places_CouSub_ConCity_SubMCD/MapServer/4/query")
CITIES = { # label used in the query -> (Census place name, state FIPS code)
"Austin, TX": ("Austin city", "48"),
"Denver, CO": ("Denver city", "08"),
"Columbus, OH": ("Columbus city", "39"),
}
def query(where, **params):
resp = requests.get(LAYER, params={"where": where, "f": "json", **params}, timeout=60)
resp.raise_for_status()
return resp.json()
cities = {}
for label, (name, state) in CITIES.items():
where = f"NAME='{name}' AND STATE='{state}'"
box = query(where, returnExtentOnly="true", outSR=4326)["extent"]
point = query(where, outFields="INTPTLAT,INTPTLON", returnGeometry="false")["features"][0]["attributes"]
cities[label] = {"south": round(box["ymin"], 4), "north": round(box["ymax"], 4),
"west": round(box["xmin"], 4), "east": round(box["xmax"], 4),
"lat": float(point["INTPTLAT"]), "lon": float(point["INTPTLON"])}
print(label, cities[label])
with open("cities.json", "w", encoding="utf-8") as f:
json.dump(cities, f, indent=2)
It printed (layer 4 is Incorporated Places, January 1, 2026 vintage):
Austin, TX {'south': 30.0756, 'north': 30.5167, 'west': -97.9384, 'east': -97.5276, 'lat': 30.2986219, 'lon': -97.7541339}
Denver, CO {'south': 39.6143, 'north': 39.9142, 'west': -105.1099, 'east': -104.5996, 'lat': 39.7618502, 'lon': -104.8811054}
Columbus, OH {'south': 39.8087, 'north': 40.1573, 'west': -83.2108, 'east': -82.7714, 'lat': 39.9873674, 'lon': -82.9851797}
Outside the US, use your national mapping agency's boundaries, or a center point and a radius you choose.
Step 1: Search Google Maps results
Send one POST request to /maps per query, with gl: "us", hl: "en" and pages: 2. The function retries what is safe to retry (429 is never charged; 502 and 503 are refunded), polls when a search answers 202, and saves each response, so a second run reads the file instead of paying again. The imports are in the full code below.
API = "https://api.bestserp.com"
CATEGORIES = ["yoga studio", "pilates studio", "gym"]
CITIES = json.loads(Path("cities.json").read_text(encoding="utf-8")) # made by city_boxes.py
PAGES = 2 # /maps returns 10 listings per page; each page costs 1 credit
RAW = Path("raw")
def search_maps(q):
headers = {"X-API-KEY": os.environ["BESTSERP_API_KEY"]}
body = {"q": q, "gl": "us", "hl": "en", "pages": PAGES}
for attempt in range(4):
resp = requests.post(f"{API}/maps", headers=headers, json=body, timeout=130)
if resp.status_code == 202: # still running: poll the request ID
request_id = resp.json()["requestId"]
while resp.status_code == 202:
time.sleep(3)
resp = requests.get(f"{API}/requests/{request_id}", headers=headers, timeout=130)
if resp.status_code == 200:
return resp.json()
if resp.status_code in (429, 502, 503): # 429 is never charged; 502 and 503 are refunded
time.sleep(int(resp.headers.get("Retry-After", 10)))
continue
resp.raise_for_status() # 400, 401, 402: fix the request, do not retry
raise RuntimeError(f"{q!r} still failing after {attempt + 1} attempts")
def fetch(category, city):
q = f"{category} in {city}" # no city parameter: the city goes into the query
path = RAW / (re.sub(r"\W+", "-", q.lower()).strip("-") + ".json")
if path.exists(): # already paid for: reuse it
return json.loads(path.read_text(encoding="utf-8"))
data = search_maps(q)
data["searchedAt"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
RAW.mkdir(exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
print(f"{q}: {len(data['places'])} listings, {data['credits']} credits, cached={data['cached']}")
return data
def run_grid():
rows, credits = [], 0
for city in CITIES:
for category in CATEGORIES:
data = fetch(category, city)
credits += data["credits"]
for place in data["places"]:
rows.append({**place, "query": data["searchParameters"]["q"], "city": city,
"searchedAt": data["searchedAt"]})
return rows, credits
Our run on November 17, 2026 (from 16:03 UTC) printed:
yoga studio in Austin, TX: 20 listings, 2 credits, cached=False
pilates studio in Austin, TX: 20 listings, 2 credits, cached=False
gym in Austin, TX: 20 listings, 2 credits, cached=False
yoga studio in Denver, CO: 20 listings, 2 credits, cached=False
pilates studio in Denver, CO: 20 listings, 2 credits, cached=False
gym in Denver, CO: 20 listings, 2 credits, cached=False
yoga studio in Columbus, OH: 20 listings, 2 credits, cached=False
pilates studio in Columbus, OH: 20 listings, 2 credits, cached=False
gym in Columbus, OH: 20 listings, 2 credits, cached=False
All 9 searches succeeded on the first attempt, each processed in 4.4 to 6.0 seconds (median 5.5); the grid ran in 55 seconds. One listing, its link shortened:
{
"position": 1,
"title": "Summit Strong",
"address": "925 Lincoln Street",
"category": "Gym",
"rating": 4.4,
"ratingCount": 228,
"hours": "Open · Closes 9 PM",
"latitude": 39.731244,
"longitude": -104.986622,
"placeId": "ChIJu2pXICh_bIcRYsSmFLkPApI",
"cid": "10520988967080739938",
"link": "https://www.google.com/maps/place/Summit+Strong/data=!4m7!3m6!..."
}
All 180 listings had a street address, category, rating, coordinates, a ChIJ... place ID and a CID (fields in the /maps reference). We leave hours out: it is the open or closed status at search time, not a timetable.
Step 2: De-duplicate and clean
De-duplicate on cid, the numeric ID of a Google Maps listing, with the place ID as a fallback; never on the name alone. The function keeps one row per CID and records every query that found it.
def dedupe(rows):
leads = {}
for r in rows:
key = r.get("cid") or r.get("placeId") or f"{r['title']}|{r.get('address', '')}".lower()
if key in leads: # same business found by another query: remember the query, keep one row
leads[key]["queries"].append(r["query"])
leads[key]["cities"].add(r["city"])
continue
leads[key] = {"name": r["title"], "category": r.get("category", ""), "address": r.get("address", ""),
"rating": r.get("rating", ""), "reviews": r.get("ratingCount", ""),
"latitude": r.get("latitude"), "longitude": r.get("longitude"),
"cid": r.get("cid", ""), "place_id": r.get("placeId", ""), "maps_url": r.get("link", ""),
"queries": [r["query"]], "cities": {r["city"]}, "searched_at": r["searchedAt"]}
return list(leads.values())
The CID caught 1 duplicate in 180 listings, and not where we expected it: a Denver yoga studio appeared at positions 1 and 9 of the same query, as "2538 West 32nd Avenue" and as "2538 W 32nd Ave A". A name-and-address key would have kept both. The three categories did not overlap at all.
Names fail the other way: 7 names covered 21 different CIDs, such as five 24 Hour Fitness locations, so a name key would have deleted 14 real locations. CIDs miss some cases too. Two pairs of leads shared a street address with different CIDs: a yoga and a pilates studio in one building, and two near-identical gym names. Flag shared addresses for a person to review.
Check that each lead is in the target city
Drop any listing whose coordinates fall outside the bounding box of the city you searched: with no city parameter, Google decides what "in Austin" means.
def km_between(lat1, lon1, lat2, lon2): # haversine distance
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(lon2 - lon1) / 2) ** 2)
return 6371 * 2 * math.asin(math.sqrt(a))
def check_location(leads):
kept, outside = [], []
for lead in leads:
lat, lon = lead["latitude"], lead["longitude"]
home = [c for c in sorted(lead["cities"]) if lat is not None and lon is not None
and CITIES[c]["south"] <= lat <= CITIES[c]["north"]
and CITIES[c]["west"] <= lon <= CITIES[c]["east"]]
searched = sorted(lead["cities"])[0]
lead["city"] = home[0] if home else searched
if home:
kept.append(lead)
else:
center = CITIES[searched]
lead["km_from_center"] = (round(km_between(lat, lon, center["lat"], center["lon"]))
if lat is not None and lon is not None else "")
outside.append(lead)
return kept, outside
In this run the check dropped 0 of 179 leads. It earns its place on other runs: applied to the "pharmacy in Austin" response saved for our Google Places API pricing guide at 15:41 UTC the same day, it flags 3 of 10 listings about 2,436 km away, in Manhattan. Repeated at 16:07 UTC, with and without ", TX", that query had 0 of 20 outside the box. Wrong-city listings come and go, so check every run.
Bounding box or city limits?
A box is a rectangle, so suburbs inside it pass. For a stricter test, city_limits.py tests every lead against the city's boundary polygon from the same TIGERweb layer:
import collections
import csv
import json
from pathlib import Path
import requests
LAYER = ("https://tigerweb.geo.census.gov/arcgis/rest/services/"
"TIGERweb/Places_CouSub_ConCity_SubMCD/MapServer/4/query")
CENSUS = {"Austin, TX": ("Austin city", "48"), "Denver, CO": ("Denver city", "08"),
"Columbus, OH": ("Columbus city", "39")}
def city_polygons(path=Path("city_polygons.json")):
if path.exists():
return json.loads(path.read_text(encoding="utf-8"))
rings = {}
for label, (name, state) in CENSUS.items():
resp = requests.get(LAYER, params={"where": f"NAME='{name}' AND STATE='{state}'", "returnGeometry": "true",
"outSR": 4326, "f": "json"}, timeout=120)
resp.raise_for_status()
rings[label] = resp.json()["features"][0]["geometry"]["rings"]
path.write_text(json.dumps(rings), encoding="utf-8")
return rings
def inside_rings(lon, lat, rings): # even-odd rule over every ring (holes toggle back to outside)
inside = False
for ring in rings:
for (x1, y1), (x2, y2) in zip(ring, ring[1:] + ring[:1]):
if (y1 > lat) != (y2 > lat) and lon < (x2 - x1) * (lat - y1) / (y2 - y1) + x1:
inside = not inside
return inside
if __name__ == "__main__":
polygons = city_polygons()
with open("leads.csv", encoding="utf-8-sig") as f:
leads = list(csv.DictReader(f))
outside = [lead for lead in leads
if not inside_rings(float(lead["longitude"]), float(lead["latitude"]), polygons[lead["city"]])]
print(f"{len(outside)} of {len(leads)} leads are outside city limits:",
dict(collections.Counter(lead["city"] for lead in outside)))
19 of 179 leads are outside city limits: {'Austin, TX': 2, 'Denver, CO': 1, 'Columbus, OH': 16}
Most were in suburbs: 16 of the 60 Columbus leads sat in places such as Grandview Heights, Bexley and Upper Arlington, and all 19 were within 21 km of their city's center point. Whether they belong in your list depends on your sales territory, so this test is optional.
Filter on category
The category field does not always match the query. Our "gym" searches returned 52 "Gym", 7 "Fitness center" and 1 "Personal trainer" listing; yoga and pilates matched on 119 of 120. Filter the category column for the types you serve.
Step 3: Export to CSV or Google Sheets
Write the leads with Python's csv module and the utf-8-sig encoding: the byte order mark lets Excel show accented names correctly. Rejects go to a second file with their distance from the center.
def write_csv(path, leads, extra=()):
with open(path, "w", newline="", encoding="utf-8-sig") as f: # BOM: Excel reads UTF-8 correctly
writer = csv.DictWriter(f, fieldnames=FIELDS + list(extra), extrasaction="ignore")
writer.writeheader()
for lead in leads:
writer.writerow({**lead, "queries": "; ".join(lead["queries"])})
if __name__ == "__main__":
rows, credits = run_grid()
leads = dedupe(rows)
kept, outside = check_location(leads)
write_csv("leads.csv", kept)
write_csv("outside.csv", outside, extra=["km_from_center"])
cost = credits * PRICE_PER_CREDIT
distances = sorted(lead["km_from_center"] for lead in outside if lead["km_from_center"] != "")
print(f"{len(rows)} listings -> {len(leads)} unique -> {len(kept)} inside the target city "
f"({len(outside)} outside, km from the center: {distances})")
print(f"{credits} credits = ${cost:.4f}, or ${cost / len(kept) * 1000:.3f} per 1,000 leads")
The last two lines of our run:
180 listings -> 179 unique -> 179 inside the target city (0 outside, km from the center: [])
18 credits = $0.0090, or $0.050 per 1,000 leads
Here are 10 of the 179 rows of leads.csv, opened in a spreadsheet:

In Google Sheets, choose File > Import, upload leads.csv and pick "Insert new sheets" or "Replace current sheet". To refresh the list from inside Sheets without a server, our Apps Script guide for Google Sheets calls the same API from the sheet. Keep the queries and searched_at columns: they record where each lead came from and when.
What the results do not contain
A Google Maps result is a listing, not a contact record: the results contain no website, no phone number and no email address. The link field held a Google Maps place URL in all 180 listings.
| You might expect | In /maps results |
Where it can come from |
|---|---|---|
| Website | No: link is a Google Maps URL |
Your own research, or websiteUri in Google's Places API |
| Phone number | No | nationalPhoneNumber in Google's Places API |
| Email address | No | Your own process: inbound forms, events, customers |
| City, state and ZIP | No: address is the street line (city named in 1 of 180) |
City from your grid; formattedAddress in the Places API |
Contact details come from your own process or from Google's official Places API (New). Its Place Details method takes a place ID and can return a phone number and website, at $20 per 1,000 requests after 1,000 free a month (Place Details Enterprise; what the Google Places API costs covers every SKU). We have no Google Maps Platform billing account, so we did not test /maps place IDs there; both use the ChIJ... form.
Before you store Places API data, read section 3.2.3 of the Google Maps Platform Terms of Service: it prohibits copying and saving business names, addresses or user reviews, and caching content beyond what its service terms allow. Google's Places API policies let you keep place IDs indefinitely.
Cost per 1,000 leads
A lead list from /maps costs about $0.05 per 1,000 leads before contact details: each credit returns up to 10 listings, at $0.50 per 1,000 credits. Our run: 18 credits for 179 leads.
| Source | Price basis (November 17, 2026) | Per 1,000 leads |
|---|---|---|
BestSERP /maps, our run |
18 credits for 179 leads, $0.50 per 1,000 credits | $0.05 |
| Places API Text Search Pro | $32 per 1,000 requests after 5,000 free, 20 places each | $1.60 |
| Places API Text Search Enterprise (adds rating, phone, website) | $35 per 1,000 requests after 1,000 free, 20 places each | $1.75 |
| Place Details Enterprise, one call per lead | $20 per 1,000 requests after 1,000 free | $20.00 |
Google's figures are the first paid tier of its price list. On any source, duplicates, rejected listings and deep pages raise the real cost per lead, because every page is billed. The listings still stay a small part of the budget: 20 categories in 50 cities at 3 pages is 3,000 searches, $1.50 at list price or the free sign-up credits, for up to 30,000 listings before de-duplication. Current prices are on the pricing page.
Using a local business lead list responsibly
Using a local business lead list is governed mostly by how you contact the businesses and where they are. What follows is general information, not legal advice.
Email to US businesses: CAN-SPAM
The Federal Trade Commission's CAN-SPAM Act compliance guide (August 2023, edited January 2024, checked November 17, 2026) is direct: "The law makes no exception for business-to-business email." Its main requirements:
- No false or misleading header information, and no deceptive subject lines.
- Identify the message as an ad, and include your valid physical postal address.
- Tell recipients how to opt out, and honor an opt-out "within 10 business days".
- After an opt-out, do not sell or transfer the address, even as part of a mailing list.
- Monitor what others, such as an agency, send on your behalf.
Each separate email in violation can bring penalties of up to $53,088, according to the guide.
Businesses in the EU and UK: GDPR and PECR
Some listings describe people: our list included a "Personal trainer" and several studios named after a person. Under the EU's General Data Protection Regulation (EU) 2016/679, Article 4(1), any information relating to an identifiable person is personal data, and a sole trader's listing can be. If your list covers the EU or the UK:
- Have a lawful basis, often legitimate interests (Article 6(1)(f)), and record how you weighed it against the person's rights.
- Tell people what Article 14 requires when you did not collect their data from them.
- Respect objections: under Article 21, people can object to direct marketing at any time.
- Check the UK email rules. The Information Commissioner's Office guidance on business-to-business marketing treats sole traders and some partnerships like individuals for email marketing under PECR: you need consent or a soft opt-in.
Build the rules into the list
- Keep the source columns:
queriesandsearched_atanswer "where did you get my details?". - Keep a suppression list of opt-outs and objections, and check it before each campaign and each fresh import.
- Collect less: keep only the columns you use, and re-run the grid rather than keeping old listings.
Common problems and fixes
| Problem | Cause | Fix |
|---|---|---|
| Leads from another city or state | No city parameter; Google interprets "in Austin" | Add the state; keep the bounding-box check on every run |
| The same business twice | One CID at two positions, or found by two queries | De-duplicate on cid, then placeId |
| Suburbs in a city list | A bounding box is a rectangle | Test against the city polygon, or treat suburbs as territory |
502 or 503 |
Search failed or service busy (refunded) | Retry after Retry-After; the program does |
429 rate_limited |
Over 60 searches per minute | Wait Retry-After; the program does |
| Garbled accents in Excel | CSV saved without a byte order mark | Write with utf-8-sig |
The error codes reference and the rate limits page have the details.
Full code
Save this as leads.py next to cities.json and run python leads.py. Tested on November 17, 2026 with Python 3.12.10 and requests 2.34.2.
"""Build a local business lead list from Google Maps results (BestSERP /maps).
export BESTSERP_API_KEY=... # never hard-code the key
python city_boxes.py # once: cities.json (bounding boxes from the US Census Bureau)
python leads.py # grid -> raw/*.json -> leads.csv + outside.csv
Responses are saved in raw/, and a query whose file exists is not searched again, so a second run re-cleans
the data for free. Tested 2026-11-17 with Python 3.12.10 and requests 2.34.2.
"""
import csv
import json
import math
import os
import re
import time
from datetime import datetime, timezone
from pathlib import Path
import requests
API = "https://api.bestserp.com"
CATEGORIES = ["yoga studio", "pilates studio", "gym"]
CITIES = json.loads(Path("cities.json").read_text(encoding="utf-8")) # made by city_boxes.py
PAGES = 2 # /maps returns 10 listings per page; each page costs 1 credit
PRICE_PER_CREDIT = 0.50 / 1000 # BestSERP: $0.50 per 1,000 searches
RAW = Path("raw")
FIELDS = ["name", "category", "address", "city", "rating", "reviews", "latitude", "longitude",
"cid", "place_id", "maps_url", "queries", "searched_at"]
def search_maps(q):
headers = {"X-API-KEY": os.environ["BESTSERP_API_KEY"]}
body = {"q": q, "gl": "us", "hl": "en", "pages": PAGES}
for attempt in range(4):
resp = requests.post(f"{API}/maps", headers=headers, json=body, timeout=130)
if resp.status_code == 202: # still running: poll the request ID
request_id = resp.json()["requestId"]
while resp.status_code == 202:
time.sleep(3)
resp = requests.get(f"{API}/requests/{request_id}", headers=headers, timeout=130)
if resp.status_code == 200:
return resp.json()
if resp.status_code in (429, 502, 503): # 429 is never charged; 502 and 503 are refunded
time.sleep(int(resp.headers.get("Retry-After", 10)))
continue
resp.raise_for_status() # 400, 401, 402: fix the request, do not retry
raise RuntimeError(f"{q!r} still failing after {attempt + 1} attempts")
def fetch(category, city):
q = f"{category} in {city}" # no city parameter: the city goes into the query
path = RAW / (re.sub(r"\W+", "-", q.lower()).strip("-") + ".json")
if path.exists(): # already paid for: reuse it
return json.loads(path.read_text(encoding="utf-8"))
data = search_maps(q)
data["searchedAt"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
RAW.mkdir(exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
print(f"{q}: {len(data['places'])} listings, {data['credits']} credits, cached={data['cached']}")
return data
def run_grid():
rows, credits = [], 0
for city in CITIES:
for category in CATEGORIES:
data = fetch(category, city)
credits += data["credits"]
for place in data["places"]:
rows.append({**place, "query": data["searchParameters"]["q"], "city": city,
"searchedAt": data["searchedAt"]})
return rows, credits
def dedupe(rows):
leads = {}
for r in rows:
key = r.get("cid") or r.get("placeId") or f"{r['title']}|{r.get('address', '')}".lower()
if key in leads: # same business found by another query: remember the query, keep one row
leads[key]["queries"].append(r["query"])
leads[key]["cities"].add(r["city"])
continue
leads[key] = {"name": r["title"], "category": r.get("category", ""), "address": r.get("address", ""),
"rating": r.get("rating", ""), "reviews": r.get("ratingCount", ""),
"latitude": r.get("latitude"), "longitude": r.get("longitude"),
"cid": r.get("cid", ""), "place_id": r.get("placeId", ""), "maps_url": r.get("link", ""),
"queries": [r["query"]], "cities": {r["city"]}, "searched_at": r["searchedAt"]}
return list(leads.values())
def km_between(lat1, lon1, lat2, lon2): # haversine distance
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(lon2 - lon1) / 2) ** 2)
return 6371 * 2 * math.asin(math.sqrt(a))
def check_location(leads):
kept, outside = [], []
for lead in leads:
lat, lon = lead["latitude"], lead["longitude"]
home = [c for c in sorted(lead["cities"]) if lat is not None and lon is not None
and CITIES[c]["south"] <= lat <= CITIES[c]["north"]
and CITIES[c]["west"] <= lon <= CITIES[c]["east"]]
searched = sorted(lead["cities"])[0]
lead["city"] = home[0] if home else searched
if home:
kept.append(lead)
else:
center = CITIES[searched]
lead["km_from_center"] = (round(km_between(lat, lon, center["lat"], center["lon"]))
if lat is not None and lon is not None else "")
outside.append(lead)
return kept, outside
def write_csv(path, leads, extra=()):
with open(path, "w", newline="", encoding="utf-8-sig") as f: # BOM: Excel reads UTF-8 correctly
writer = csv.DictWriter(f, fieldnames=FIELDS + list(extra), extrasaction="ignore")
writer.writeheader()
for lead in leads:
writer.writerow({**lead, "queries": "; ".join(lead["queries"])})
if __name__ == "__main__":
rows, credits = run_grid()
leads = dedupe(rows)
kept, outside = check_location(leads)
write_csv("leads.csv", kept)
write_csv("outside.csv", outside, extra=["km_from_center"])
cost = credits * PRICE_PER_CREDIT
distances = sorted(lead["km_from_center"] for lead in outside if lead["km_from_center"] != "")
print(f"{len(rows)} listings -> {len(leads)} unique -> {len(kept)} inside the target city "
f"({len(outside)} outside, km from the center: {distances})")
print(f"{credits} credits = ${cost:.4f}, or ${cost / len(kept) * 1000:.3f} per 1,000 leads")
How we tested
- Grid: the 9
/mapssearches above, November 17, 2026, 16:03:53 to 16:04:48 UTC,gl: "us",hl: "en",pages: 2: 180 listings, 18 credits, none cached. - Location: boxes, center points (the Census "internal point") and polygons from TIGERweb's Incorporated Places layer (January 1, 2026 vintage); great-circle distances; suburbs named with TIGERweb point queries.
- Wrong-city check: "pharmacy in Austin" with and without ", TX" at 16:07 UTC (4 credits), plus the response saved for our pricing guide at 15:41 UTC.
- Software: Python 3.12.10, requests 2.34.2, Windows 10. Google prices from its price list the same day; we did not call the Places API.
Nine searches in three cities is a small sample: measure your own duplicate and rejection rates on a first run before you scale the grid.
Next steps
A local business lead list from Google Maps results is a grid, a CID key, a location check and a CSV; contact details and consent are separate work.
- Field-by-field differences: the local search data guide and Google Places vs Google Maps results.
- 20 listings per credit, without coordinates: the Google Places API page.
- First API calls from Python: Google search results in Python.