ScreenshotNeo

BlogHow-to

Screenshot Maps with Selenium and the Google Maps API

Capture rendered Google Maps views with Selenium, or generate parameter-driven images with the Static Maps API. Includes code, policies, troubleshooting, and costs.

By the ScreenshotNeo team30 September 202610 min read

Screenshot Maps with Selenium and the Google Maps API

Direct answer: use Selenium when you need a screenshot of the Google Maps view exactly as it appears in a browser, including the current viewport, zoom, overlays, controls, and application state. Use the Google Maps Static API when you only need an image built from known parameters such as center, zoom, size, markers, and paths. Selenium captures a rendered browsing context; Static Maps returns an image from an authenticated URL without JavaScript or dynamic page loading.

The choice affects implementation, legal handling, and output. A browser capture requires WebDriver, a compatible browser, and an application-specific readiness check. A Static Maps request requires an enabled Google Cloud project, billing, credentials, quota planning, and compliance with Google’s attribution and content-use policies. Neither approach should be described as universally faster or cheaper: the official sources do not provide a benchmark for that comparison.

Choose the right kind of map image

Requirement Selenium screenshot Google Maps Static API
Capture the live browser interface Yes. WebDriver captures the current browsing context or an element. No. It constructs an image from request parameters.
JavaScript and browser session Required for a Maps JavaScript view. Not required.
Viewport and UI state Reflects the selected viewport, zoom, overlays, and controls after your code sets them. Only parameters supported by the service are represented.
Setup Browser, WebDriver, application page, and readiness logic. Enabled API, billing account, credentials, URL parameters, quotas, and terms review.
Output handling PNG or another browser screenshot file, with WebDriver image data returned as Base64 by the protocol. Google-served image; Google’s FAQ says not to store and serve copies from your own website.

Selenium’s documentation calls this operation “Used to capture screenshot for current browsing context” and shows both viewport and element screenshots. Its page also cautions that screenshot behavior depends on the implementation, so do not promise identical full-page output across browsers. Read the Selenium screenshot documentation.

Capture a rendered Google Map with Selenium in Python

The following example opens a page that contains your Maps JavaScript implementation, sets a deterministic browser window, waits for an application-owned readiness marker, and saves both the map element and the viewport. Replace the example page and readiness condition with selectors and state that your application controls. The Selenium documentation does not define a universal Google Maps readiness selector.

Wait for application-owned map readiness before saving an element or viewport screenshot.
Wait for application-owned map readiness before saving an element or viewport screenshot.
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

MAP_PAGE = "https://example.com/map"
OUT_DIR = Path("screenshots")
OUT_DIR.mkdir(exist_ok=True)

options = Options()
options.add_argument("--headless=new")
options.add_argument("--window-size=1440,900")
options.add_argument("--disable-gpu")

# Ensure chromedriver and Chrome versions are compatible in your environment.
driver = webdriver.Chrome(options=options)
try:
    driver.get(MAP_PAGE)

    # Your application should set data-map-ready="true" only after it has
    # applied the intended center, zoom, overlays, and any async data.
    WebDriverWait(driver, 60).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '[data-map-ready="true"]'))
    )

    map_element = WebDriverWait(driver, 30).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "#map"))
    )

    # Element screenshot: only the rendered map container.
    map_element.screenshot(str(OUT_DIR / "map-element.png"))

    # Viewport screenshot: includes the surrounding page UI.
    driver.save_screenshot(str(OUT_DIR / "map-viewport.png"))
finally:
    driver.quit()

The readiness marker is deliberately application-specific. Set it after your map has reached the requested center and zoom, overlays have been added, and data-driven markers or routes have finished rendering. A fixed sleep(5) can be useful while diagnosing a page, but it is not proof that rendering completed: network speed, tile delivery, animation, and application state vary.

Make the browser state deterministic

  1. Set the viewport. Use a fixed window size and, when visual diffs matter, keep the same browser and device scale factor.
  2. Set map state in the page. Apply center, zoom, map type, overlays, and route data through your own application code before setting the readiness marker.
  3. Wait for state, not time. Expose a DOM attribute, status element, or JavaScript condition that your test owns.
  4. Choose element versus viewport capture. The element method excludes surrounding navigation and page chrome; save_screenshot captures the current browsing context.
  5. Close the driver. Put quit() in a finally block so failed captures do not leave browser processes running.

Capturing a canvas or a map inside an iframe

A map may be rendered on a canvas, but Selenium can still capture the element that contains it. Locate the visible map container rather than trying to read tile pixels through JavaScript. If the map is inside an iframe, wait for the frame and switch into it before locating the map:

from selenium.webdriver.support import expected_conditions as EC

frame = WebDriverWait(driver, 30).until(
    EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe.map-frame"))
)
map_element = WebDriverWait(driver, 30).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, "#map"))
)
map_element.screenshot("screenshots/iframe-map.png")
driver.switch_to.default_content()

If the frame is cross-origin, do not expect to inspect its DOM from the parent page. Switching into the frame through WebDriver is the supported route when the frame is accessible to the browser session.

Generate a parameter-driven image with Google Maps Static API

Static Maps is appropriate when the desired result can be expressed as request parameters. Google describes it as returning an image from a URL without JavaScript or dynamic page loading. A typical request supplies a center, zoom, image size, map type, and one or more markers or paths. Enable the Static Maps API in a Google Cloud project, attach a billing account, obtain credentials, and verify current quotas and pricing before deployment.

Selenium reflects rendered browser state; Static Maps builds an image from request parameters.
Selenium reflects rendered browser state; Static Maps builds an image from request parameters.
curl --get "https://maps.googleapis.com/maps/api/staticmap" \
  --data-urlencode "center=40.7484,-73.9857" \
  --data-urlencode "zoom=14" \
  --data-urlencode "size=800x500" \
  --data-urlencode "maptype=roadmap" \
  --data-urlencode "markers=color:red|40.7484,-73.9857" \
  --data-urlencode "key=YOUR_GOOGLE_MAPS_KEY" \
  --output static-map.png

Use the parameter names and limits in the current Static Maps reference for your account and region. Google’s best-practices guide states a maximum total request URL length of 16,384 characters, recommends HTTPS, and recommends using an API key with a digital signature. Keep credentials out of source control and logs.

Static Maps request checklist

  • Enable the required API in the intended Cloud project.
  • Attach a billing account and confirm the current pricing tier and quotas.
  • Restrict the key to the APIs, applications, and hosts that need it.
  • Use HTTPS and a digital signature where Google’s guidance requires or recommends one.
  • URL-encode addresses, labels, paths, and other user-controlled values.
  • Keep the complete URL below the documented 16,384-character limit.
  • Preserve required Google attribution and notices in the user-facing context.

Attribution, caching, and permitted use

A screenshot does not remove Google Maps Platform obligations. Google’s Maps JavaScript API policies require clear, legible attribution and describe restrictions on pre-fetching, caching, and storage. They also require publicly accessible Terms of Use and a Privacy Policy that incorporate Google’s terms and policies. Place IDs are treated differently from most cached content, but review the current policy for the exact data you handle.

Google’s FAQ says a website may not store and serve copies generated by Maps Static API. The compliant pattern it describes is to reference the Static API directly from the page so Google serves the image to the end user. Do not build a permanent image archive from Static API responses without confirming that your use is permitted. Place names returned from user interactions also have context-specific restrictions; do not capture and persist them for an unrelated context.

Policy language and billing terms can change. Review the live Maps JavaScript API policies, Google Maps Platform FAQ, Static Maps overview, and Static API best practices before publishing or retaining images.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. It is useful when you want the rendered page captured through a single request rather than maintaining browser and WebDriver infrastructure. The service accepts a URL and returns PNG, JPEG, WebP, or PDF. Its cleanup steps can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled.

Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

For a one-call capture, see the ScreenshotNeo API documentation:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo includes full-page capture with lazy images loaded, element capture by CSS selector, dark mode, device presets or custom viewports, retina scale, custom CSS and JavaScript, clicks, selector or network-idle waits, blocked ads and requests, custom headers and cookies, timezone and geolocation, transparent backgrounds, resizing, selectable cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameters used by other screenshot APIs also work, which can simplify migration.

There is a free plan with 1,000 screenshots per month and no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account.

Troubleshooting Selenium captures

Symptom Likely cause Fix
Blank or partially drawn map Capture ran before your map state or tiles were ready. Set an application-owned readiness marker after center, zoom, overlays, and data are complete. Increase the explicit wait timeout only after fixing the condition.
Wrong zoom or center The screenshot captured the default map state or an animation in progress. Set state through your map code, disable or await transitions, then signal readiness.
NoSuchElementException The selector is wrong, the element is inside an iframe, or the page has not rendered it. Wait for visibility, inspect the actual DOM, and switch into the iframe when applicable.
SessionNotCreatedException Browser and driver versions or options are incompatible. Install a compatible WebDriver/browser pair and verify headless arguments for the installed browser.
Element screenshot is clipped The element has a fixed viewport or overflow region. Capture the intended container, adjust its CSS for the capture route, or use a viewport screenshot when surrounding content is required.
Intermittent timeout External tiles, application data, or network conditions vary. Wait on a meaningful state, collect browser logs, retry only idempotent captures, and record the URL and state that failed.

Troubleshooting Static Maps requests

  • Authentication or request denied: verify that the API is enabled, the key belongs to the billed project, restrictions allow the calling host, and a required signature is valid.
  • Unexpected image or missing marker: URL-encode every parameter and check latitude, longitude, zoom, size, marker, and path syntax against the current reference.
  • Request too long: simplify markers and paths or use a different representation before reaching the 16,384-character limit.
  • Quota or billing error: check current Cloud quotas, billing status, and regional pricing; do not infer today’s cost from an old estimate.
  • Policy concern: preserve attribution, avoid serving stored Static API copies, and review the current terms for caching and user-interaction data.

Performance, reliability, and cost planning

Selenium starts a browser, loads JavaScript, downloads map assets, and waits for your application state. Keep sessions short, reuse a driver only when isolation is safe, and avoid arbitrary long delays. Capture only the element you need when a full page is unnecessary. For repeatable visual output, pin the browser configuration and viewport and record the map state used for each image.

Static Maps removes browser startup and dynamic readiness work, but it remains subject to request quotas, URL limits, credentials, and Google’s service terms. It is a good fit for parameterized images that can be regenerated on demand. Neither source establishes a universal latency or price advantage, so measure your own workload and consult current billing pages.

For either method, make failures observable: store HTTP status or WebDriver exceptions, target URL, requested center and zoom, viewport, and a timestamp. Retry transient network failures with a bounded policy; do not retry authentication, policy, or malformed-parameter errors until the cause is corrected.

FAQ

How do I take a screenshot with Selenium?

Open the page with WebDriver, wait until your application reports that the map is ready, then call driver.save_screenshot("map.png") for the viewport or element.screenshot("map.png") for one element.

Can Selenium save a PNG?

Yes. Selenium’s Python binding accepts a filename ending in .png for both driver and element screenshots.

Can Static Maps reproduce an interactive control panel?

No. Static Maps creates an image from request parameters. Use Selenium when controls, overlays, or the surrounding application interface must appear exactly as rendered.

Should I cache a Static Maps response?

Google’s FAQ says not to store and serve copies generated by Static API. Follow the current FAQ and Maps Platform policies for your use case.

What if I need screenshots for an AI agent?

ScreenshotNeo’s MCP server provides take_screenshot, get_page_info, and capture_pdf to MCP clients such as Claude and Cursor, avoiding custom browser orchestration for those workflows.