Google Maps Data Extractor Chrome Extension
Here's a comprehensive solution for a Chrome extension that extracts business data from Google Maps based on title and city inputs.
Manifest File (manifest.json)
{
"manifest_version": 3,
"name": "Google Maps Data Extractor",
"version": "1.0",
"description": "Extracts business data from Google Maps based on search queries",
"permissions": [
"activeTab",
"storage",
"downloads",
"scripting"
],
"host_permissions": [
"https://www.google.com/maps/*"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/icon16.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
}
},
"icons": {
"16": "images/icon16.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
}
}
Popup HTML (popup.html)
<!DOCTYPE html>
<html>
<head>
<title>Google Maps Extractor</title>
<style>
body {
width: 400px;
padding: 15px;
font-family: Arial, sans-serif;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input, textarea {
width: 100%;
padding: 8px;
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 4px;
}
textarea {
height: 100px;
resize: vertical;
}
button {
background-color: #4285f4;
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
width: 100%;
font-weight: bold;
}
button:hover {
background-color: #3367d6;
}
.status {
margin-top: 15px;
padding: 10px;
border-radius: 4px;
display: none;
}
.success {
background-color: #e6f4ea;
color: #137333;
}
.error {
background-color: #fce8e6;
color: #c5221f;
}
</style>
</head>
<body>
<div class="form-group">
<label for="title">Business Title/Keyword:</label>
<input type="text" id="title" placeholder="e.g. Restaurants, Hotels, etc.">
</div>
<div class="form-group">
<label for="cities">Cities (one per line):</label>
<textarea id="cities" placeholder="New York
London
Tokyo"></textarea>
</div>
<button id="extract">Extract Data</button>
<div id="status" class="status"></div>
<script src="popup.js"></script>
</body>
</html>
Popup JavaScript (popup.js)
document.getElementById('extract').addEventListener('click', async () => {
const title = document.getElementById('title').value.trim();
const citiesText = document.getElementById('cities').value.trim();
if (!title || !citiesText) {
showStatus('Please enter both title and cities', 'error');
return;
}
const cities = citiesText.split('\n').map(c => c.trim()).filter(c => c);
showStatus('Starting extraction process...', 'success');
try {
// Open a new window for extraction
const extractionWindow = window.open('', '_blank');
// Send data to background script
chrome.runtime.sendMessage({
action: 'startExtraction',
title: title,
cities: cities
});
showStatus('Extraction in progress. Please keep the new window open.', 'success');
} catch (error) {
showStatus('Error: ' + error.message, 'error');
console.error(error);
}
});
function showStatus(message, type) {
const statusElement = document.getElementById('status');
statusElement.textContent = message;
statusElement.className = 'status ' + type;
statusElement.style.display = 'block';
}
Background Script (background.js)
let currentExtraction = null;
let extractedData = [];
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'startExtraction') {
startExtraction(request.title, request.cities);
sendResponse({status: 'started'});
}
return true;
});
async function startExtraction(title, cities) {
extractedData = [];
// Create a new window for extraction
const extractionWindow = await chrome.windows.create({
url: 'https://www.google.com/maps',
type: 'popup',
width: 1200,
height: 800
});
currentExtraction = {
windowId: extractionWindow.id,
title: title,
cities: cities,
currentCityIndex: 0,
tabId: extractionWindow.tabs[0].id
};
// Wait for the window to load
await new Promise(resolve => setTimeout(resolve, 3000));
// Start processing the first city
processNextCity();
}
async function processNextCity() {
if (!currentExtraction) return;
if (currentExtraction.currentCityIndex >= currentExtraction.cities.length) {
// All cities processed, download the data
downloadData();
currentExtraction = null;
return;
}
const city = currentExtraction.cities[currentExtraction.currentCityIndex];
const searchQuery = `${currentExtraction.title} in ${city}`;
try {
// Execute script in the tab to perform the search
await chrome.scripting.executeScript({
target: {tabId: currentExtraction.tabId},
func: performSearch,
args: [searchQuery]
});
// Wait for results to load
await new Promise(resolve => setTimeout(resolve, 5000));
// Scroll and extract data
await chrome.scripting.executeScript({
target: {tabId: currentExtraction.tabId},
func: scrollAndExtractData,
args: [city]
});
// Move to next city
currentExtraction.currentCityIndex++;
processNextCity();
} catch (error) {
console.error('Error processing city:', city, error);
// Move to next city even if error
currentExtraction.currentCityIndex++;
processNextCity();
}
}
function performSearch(query) {
const searchBox = document.getElementById('searchboxinput');
if (searchBox) {
searchBox.value = query;
searchBox.dispatchEvent(new Event('input', { bubbles: true }));
const searchButton = document.getElementById('searchbox-searchbutton');
if (searchButton) {
searchButton.click();
}
}
}
async function scrollAndExtractData(city) {
return new Promise((resolve) => {
const scrollInterval = setInterval(() => {
const listContainer = document.querySelector('[role="feed"]');
if (listContainer) {
listContainer.scrollTop = listContainer.scrollHeight;
// Check if we've reached the end
if (listContainer.scrollHeight - listContainer.scrollTop - listContainer.clientHeight < 10) {
clearInterval(scrollInterval);
extractData(city).then(resolve);
}
}
}, 1000);
});
}
function extractData(city) {
return new Promise((resolve) => {
const items = document.querySelectorAll('[role="article"]');
const cityData = [];
items.forEach(item => {
try {
const nameElement = item.querySelector('.fontHeadlineSmall');
const addressElement = item.querySelector('.W4Efsd:not(:has(span))');
const phoneElement = Array.from(item.querySelectorAll('.W4Efsd span')).find(el =>
el.textContent.includes('+') || el.textContent.match(/\d{3}[-.]\d{3}[-.]\d{4}/)
);
const websiteElement = item.querySelector('a[href*="http"]');
const ratingElement = item.querySelector('.MW4etd');
const reviewsElement = item.querySelector('.UY7F9');
const data = {
name: nameElement ? nameElement.textContent.trim() : '',
address: addressElement ? addressElement.textContent.replace(/\n/g, ', ').trim() : '',
phone: phoneElement ? phoneElement.textContent.trim() : '',
website: websiteElement ? websiteElement.href : '',
rating: ratingElement ? ratingElement.textContent.trim() : '',
reviews: reviewsElement ? reviewsElement.textContent.trim() : '',
city: city,
timestamp: new Date().toISOString()
};
cityData.push(data);