ScreenshotNeo

BlogHow-to

How to Capture Google Maps with Wkhtmltoimage and IMGKit

Capture complete Google Maps views with wkhtmltoimage and IMGKit, including API setup, JavaScript timing, headless Linux fixes, and troubleshooting.

By the ScreenshotNeo team30 September 20268 min read

How to Capture Google Maps with Wkhtmltoimage and IMGKit

Direct answer: create a map page with an explicit width and height, load the Google Maps JavaScript API with a valid key, wait until the map tiles or WebGL content are ready, then render that page with wkhtmltoimage through IMGKit. Set the output format and viewport explicitly. On a headless Linux server, install the renderer and configure xvfb when required.

Google Maps is JavaScript-driven. Google documents raster maps as server-generated pixel tiles and vector maps as vector tiles drawn in the browser with WebGL, so a capture taken before JavaScript and map rendering finish can be blank or incomplete. See the Google Maps JavaScript documentation and official API loading guide.

1. Prerequisites

  • A Google Cloud project with the Maps JavaScript API enabled.
  • An API key authorized for the domains or server that will load the map.
  • wkhtmltoimage installed and available on PATH, or its absolute path configured in IMGKit.
  • Python with imgkit, or Ruby with the IMGKit gem.
  • A page with fixed map dimensions. A map container without an explicit height commonly renders as zero pixels tall.

If you use a map ID, Google recommends associating that map ID and API key with the same project.

2. Build a capture-ready map page

Save this as map.html. Replace YOUR_GOOGLE_MAPS_KEY with your key and adjust the center, zoom, and dimensions for your use case.

The capture path: initialize the map, wait for tiles or WebGL content, then render the finished page.
The capture path: initialize the map, wait for tiles or WebGL content, then render the finished page.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Map capture</title>
  <style>
    html, body { margin: 0; width: 100%; height: 100%; }
    #map { width: 1200px; height: 800px; }
  </style>
</head>
<body>
  <div id="map"></div>
  <script>
    let mapReady = false;

    function initMap() {
      const map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: 40.7484, lng: -73.9857 },
        zoom: 13,
        mapTypeControl: false,
        streetViewControl: false,
        fullscreenControl: false
      });

      // Signal to the renderer after the map has emitted its first idle event.
      google.maps.event.addListenerOnce(map, "idle", () => {
        mapReady = true;
        document.documentElement.setAttribute("data-map-ready", "true");
      });
    }
  </script>
  <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_KEY&callback=initMap">
  </script>
</body>
</html>

The idle event is a useful page-side signal, but IMGKit still needs a renderer delay because tile painting can continue after JavaScript callbacks. Choose the delay for your page and deployment.

3. Capture with Python IMGKit

Install the wrapper and renderer. Package names vary by operating system; verify that wkhtmltoimage --version succeeds.

python -m pip install imgkit
wkhtmltoimage --version

Render the local file with a fixed viewport, PNG output, UTF-8, and a JavaScript delay:

import imgkit

options = {
    "format": "png",
    "encoding": "UTF-8",
    "width": 1200,
    "height": 800,
    "javascript-delay": 3000,
    "quiet": "",
}

imgkit.from_file("map.html", "map.png", options=options)

IMGKit also accepts an HTML string or URL:

import imgkit

html = open("map.html", encoding="utf-8").read()
imgkit.from_string(html, "map-from-string.png", options={
    "format": "png",
    "encoding": "UTF-8",
    "width": 1200,
    "height": 800,
    "javascript-delay": 3000,
})

imgkit.from_url(
    "https://example.com/map-page",
    "map-from-url.png",
    options={"format": "png", "width": 1200, "height": 800, "javascript-delay": 3000},
)

If the executable is not on PATH, configure its location:

import imgkit

config = imgkit.config(wkhtmltoimage="/usr/local/bin/wkhtmltoimage")
imgkit.from_file("map.html", "map.png", config=config, options={
    "format": "png",
    "width": 1200,
    "height": 800,
    "javascript-delay": 3000,
})

4. Capture with Ruby IMGKit

IMGKit’s Ruby interface accepts a URL, file, or HTML string and can write PNG, JPG, or JPEG output.

gem install imgkit
wkhtmltoimage --version
require "imgkit"

kit = IMGKit.new(File.read("map.html"), format: :png)
kit.to_file("map.png")

For a URL or HTML string:

require "imgkit"

from_url = IMGKit.new("https://example.com/map-page", format: :png)
from_url.to_file("map-url.png")

html = File.read("map.html", encoding: "UTF-8")
from_string = IMGKit.new(html, format: :png)
from_string.to_file("map-string.png")

Set renderer options when your page needs a larger viewport or additional JavaScript time. The exact option names follow wkhtmltoimage and the IMGKit binding version you install.

5. Run wkhtmltoimage directly

IMGKit is a wrapper around the command-line binary. Direct invocation helps isolate whether a failure is in the wrapper or in the renderer itself.

wkhtmltoimage \
  --format png \
  --width 1200 \
  --height 800 \
  --javascript-delay 3000 \
  --encoding UTF-8 \
  map.html map-direct.png

For a remote page:

wkhtmltoimage \
  --format png \
  --width 1200 \
  --height 800 \
  --javascript-delay 3000 \
  https://example.com/map-page map-url.png

6. Headless Linux and xvfb

Some headless deployments need a virtual display. Install and run the capture through xvfb-run as described by the IMGKit and wkhtmltoimage packaging instructions:

xvfb-run -a wkhtmltoimage \
  --format png \
  --width 1200 \
  --height 800 \
  --javascript-delay 3000 \
  map.html map.png

With Python, invoke the program that starts your worker under xvfb-run, or configure the virtual display in the service manager. If you see a display or Qt platform error, confirm that Xvfb is installed, the display is available to the process, and the renderer binary matches the host architecture.

7. Choose dimensions, format, and timing

Setting Recommendation Why it matters
Map CSS width and height Set explicit values such as 1200 × 800 Prevents a zero-height or clipped map.
Renderer width and height Match the map’s intended viewport Controls visible labels, tile count, and crop.
Format PNG for labels and lossless output; JPG for smaller photographic output Explicit format avoids extension and MIME surprises.
JavaScript delay Start around 3000 ms, then tune for the page Allows API loading, tile requests, and painting to complete.
Encoding UTF-8 Preserves page text and symbols.

There is no universal delay for every map, network, or host. A slow API response, vector WebGL rendering, or busy server may need more time. For repeatable output, keep center, zoom, dimensions, map styling, and timing stable.

Explicit dimensions prevent blank and clipped map captures.
Explicit dimensions prevent blank and clipped map captures.

8. Troubleshooting

Blank map or an empty image

  • Check that the API key is valid, the Maps JavaScript API is enabled, and the project has the required billing configuration.
  • Open the same HTML in a browser and inspect the console for key, authorization, or loader errors.
  • Confirm that the capture host can reach Google Maps API endpoints and tile servers.
  • Verify JavaScript execution is enabled and increase javascript-delay.
  • Ensure #map has an explicit nonzero height.

Missing labels or partial tiles

Increase the viewport and delay. Capture after the map’s idle or tile-loading signal rather than immediately after page load. Vector maps require client-side WebGL rendering; an environment that cannot render the required content may produce incomplete output.

No wkhtmltoimage executable found

Install the binary, add it to PATH, or pass its absolute path through IMGKit configuration. Confirm the configured path is executable by the service user.

Headless display or Qt errors

Install Xvfb and run the renderer with xvfb-run -a. Check that the process has permission to use the display and that no conflicting display variable is masking the virtual display.

Wrong output type

Set format explicitly in IMGKit or --format with wkhtmltoimage. Use png, jpg, or jpeg and make the file extension match.

Clipped map

Give the map container fixed dimensions and match them with renderer width and height. If you need a crop, configure the renderer’s crop options after confirming the full map renders.

API key works in a browser but not on the server

Review HTTP referrer or IP restrictions. The server’s egress address and the page origin may differ from your local browser. Use the official loader and initialization structure from Google’s guide.

Intermittent failures

Record renderer stderr, HTTP status, page console errors, and capture duration. Retry transient network failures with a bounded backoff, but do not hide persistent key or authorization errors. Keep a stable renderer version and image dimensions for easier diagnosis.

9. Performance and reliability practices

  • Reuse a warm worker process where your deployment allows it; starting a browser-like renderer for every request adds overhead.
  • Keep the page small and remove unrelated scripts, fonts, and widgets from the capture route.
  • Use a fixed viewport and zoom so tile count and output size stay predictable.
  • Wait only as long as needed for the map’s readiness signal and final painting.
  • Set request and job timeouts above the expected API and tile loading time, then fail clearly when exceeded.
  • Capture at a controlled concurrency. Excessive parallel tile loads can increase latency or trigger API limits.
  • Store the source HTML, renderer version, options, map center, zoom, and timestamp with generated assets when reproducibility matters.

10. Cost and usage considerations

Google Maps Platform usage and any cloud or server resources used to run wkhtmltoimage are separate from IMGKit, which is a wrapper. Your total cost depends on Maps API usage, compute time, image storage, and network transfer. Review the current Google Maps Platform pricing and terms for your project before production deployment.

11. Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF, so you do not need to package wkhtmltoimage, IMGKit, or xvfb for this capture path. Read the ScreenshotNeo API documentation for all options.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://maps.google.com -o map.webp

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://maps.google.com"},
    timeout=90,
)
r.raise_for_status()
open("map.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://maps.google.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('map.webp', data);

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Create a free ScreenshotNeo account and start with 1,000 screenshots a month at no cost.

12. FAQ

Can wkhtmltoimage capture a Google Maps vector map?

It can capture what the rendering environment successfully paints, but vector maps use client-side WebGL. If WebGL support or timing is insufficient, use a raster configuration or a renderer that supports the required browser features.

Should I use PNG or JPEG?

Use PNG when crisp labels and lossless map lines matter. Use JPEG when a smaller file is more important and some compression is acceptable.

Why does the same delay work locally but fail in production?

Network latency, CPU speed, API responses, virtual display setup, and renderer versions differ. Tune timing on the deployment environment and log failures instead of relying on a fixed local delay.

Can I capture only one map element?

Set the page or crop dimensions around the map container, then render with matching width and height. Remove surrounding layout that can change the crop.

Do I need IMGKit if wkhtmltoimage works?

No. IMGKit adds Python or Ruby bindings and option handling. Direct wkhtmltoimage invocation is useful for simple scripts and for isolating wrapper configuration problems.