class GoogleStaticMap

Main class for creating a static map. Create an instance, Set attributes that describe properties of the map. Then call url to get a URL that you can use as the src of an img tag. You can also call #get_map to actually download the map from Google, and optionally write it to a file.



API Key - see for details Note that if this is set, you cannot provide a client ID


MapLocation for the center of the map. If this is not specified, the map will zoom to the markers


Channel - identifier channel for tracking API source in enterprise tools

see for details

ClientId for business customers - see for details Note that if this is set, you cannot provide an API key.


format of the image:

  • png8 - 8 bit PNG (default)

  • png32 - 32 bit PNG

  • gif

  • jpg

  • jpg-baseline - non-progressive JPEG


Height of resulting image in pixels, defaults to 350, maximum 640


Language - :en, :ja

see for details

Type of map to create:

  • roadmap (default)

  • satellite

  • terrain

  • hybrid - satellite imagery with roads


An optional array of MapMarker instances


An optional array of MapPath instances and/or MapPolygon instances to draw


In case when some parameter should be inserted manually For example, using tool and inserting generated style as is


The private key, also known as the URL signing secret, is used to to generate the signature parameter in the URL. This is required if you are using a client ID, or a premium API key, and is optional if you are using a standard API key. See for more details


If you need to use a proxy server to reach Google, set the name/address of the proxy server here


If #proxy_address is set, set this to the port of the proxy server


1, 2, or 4 for Maps API Premier customers. Defaults to 1. Makes everything in the image appear larger, useful for displaying on high res mobile screens. When setting this, the image's actual width and height in pixels will be scale * width and scale * height


Applications that determine the user's location via a sensor must set this to true, defaults to false


Styles - see styles is should be represented as array of objects [{feature: 'featureArgument, element: 'elementArgument', rule1: 'rule1Arguement', rule2: 'rule2Arguement', …}, …]


Width of resulting image in pixels, defaults to 500, maximum 640


0 (the whole world) to 21 (individual buildings)

Public Class Methods

new(attrs={}) click to toggle source

Takes an optional hash of attributes

# File lib/googlestaticmap.rb, line 101
def initialize(attrs={})
  defaults = {:width => 500, :height => 350, :markers => [],
              :sensor => false, :maptype => "roadmap", :paths => [],
              :proxy_port => nil, :proxy_address => nil, :api_key => nil,
              :client_id => nil, :private_key => nil, :language => nil}

  attributes = defaults.merge(attrs)
  attributes.each {|k,v| self.send("#{k}=".to_sym,v)}

Public Instance Methods

get_map(output_file=nil, protocol='http') click to toggle source

Connects to Google, retrieves the map, and returns the bytes for the image. Optionally, pass it an output name and the contents will get written to this file name output_file - optionally give the name of a file to write the output to.

Pass nil to not write the output to a file

protocol - specify http or https here for the protocol to retrieve the

map with. Defaults to http

return value - the binary data for the map

# File lib/googlestaticmap.rb, line 169
def get_map(output_file=nil, protocol='http')
  protocol = 'http' unless protocol == 'http' || protocol == 'https'
  port = protocol == 'https' ? 443 : 80
  http = Net::HTTP.Proxy(@proxy_address,@proxy_port).new("", port)
  http.use_ssl = protocol == 'https'

  resp = http.get2(relative_url(protocol))
  if resp && resp.is_a?(Net::HTTPSuccess)
    if output_file, "wb") {|f| f << resp.body }
    if resp
      raise"Error encountered while retrieving google map, code #{resp.code}, text #{resp.body}")
      raise"Error while retrieve google map, no response")
get_styles() click to toggle source
# File lib/googlestaticmap.rb, line 190
def get_styles do |style|
    values = do |(key, value)|
    ["style", values.join(CGI.escape('|'))]
relative_url(protocol='http') click to toggle source

Returns the URL to retrieve the map, relative to Example - “/maps/api/staticmap?params…”

# File lib/googlestaticmap.rb, line 156
def relative_url(protocol='http')
  url(protocol).gsub(/[^\/]*\/\/maps\.googleapis\.com/, "")
url(protocol='http') click to toggle source

Returns the full URL to retrieve this static map. You can use this as the src for an img to display an image directly on a web page Example - “…” protocol can be 'http', 'https' or :auto. Specifying :auto will not return

a protocol in the URL ("//"), allowing the browser to
select the appropriate protocol (if the page is loaded with https, it will
use https). Defaults to http
# File lib/googlestaticmap.rb, line 118
def url(protocol='http')
  unless @center || @markers.length > 0 || @paths.length > 0
    raise"Need to specify either a center, markers, or a path")
  if !@api_key.nil? && !@client_id.nil?
    rasise"You cannot specify both an API key and a client ID, only specify one")
  if !@client_id.nil? && @private_key.nil?
    raise"private_key must be specified if using a client ID")
  protocol = 'http' unless protocol == 'http' || protocol == 'https' ||
                           protocol == :auto
  protocol = protocol == :auto ? '' : protocol + ":"
  base = "#{protocol}//"
  path = "/maps/api/staticmap?"
  attrs = GoogleStaticMapHelpers.safe_instance_variables(self,
            ["markers", "paths", "width", "height", "center",
             "proxy_address", "proxy_port", "api_key", "client_id",
             "private_key", "styles", "plain_string"],
            :cgi_escape_values => true).to_a
  attrs << ["size", "#{@width}x#{@height}"] if @width && @height
  @markers.each {|m| attrs << ["markers",m.to_s] }
  @paths.each {|p| attrs << ["path",p.to_s] }
  attrs << ["center", @center.to_s] if !@center.nil?
  attrs << ["key", @api_key] if !@api_key.nil?
  attrs << ["client", @client_id] if !@client_id.nil?
  get_styles.each { |style| attrs << style } if !@styles.nil?
  path << attrs.sort_by {|k,v| k}.collect {|attr| "#{attr[0]}=#{attr[1]}"}.join("&")
  path << "&#{@plain_string}" if !@plain_string.nil?
  if (!@api_key.nil? || !@client_id.nil?) && !@private_key.nil?
    signature = GoogleStaticMapHelpers.sign(path, @private_key)
    path << "&signature=" << signature
  base + path