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.

Attributes

api_key[RW]

API Key - see developers.google.com/maps/documentation/static-maps/get-api-key#key for details Note that if this is set, you cannot provide a client ID

center[RW]

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

channel[RW]

Channel - identifier channel for tracking API source in enterprise tools

see https://developers.google.com/maps/documentation/business/clientside/quota for details
client_id[RW]

ClientId for business customers - see developers.google.com/maps/documentation/static-maps/get-api-key#key for details Note that if this is set, you cannot provide an API key.

format[RW]

format of the image:

  • png8 - 8 bit PNG (default)

  • png32 - 32 bit PNG

  • gif

  • jpg

  • jpg-baseline - non-progressive JPEG

height[RW]

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

language[RW]

Language - :en, :ja

see https://developers.google.com/maps/documentation/static-maps/intro for details
maptype[RW]

Type of map to create:

  • roadmap (default)

  • satellite

  • terrain

  • hybrid - satellite imagery with roads

markers[RW]

An optional array of MapMarker instances

paths[RW]

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

private_key[RW]

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 developers.google.com/maps/documentation/static-maps/get-api-key for more details

proxy_address[RW]

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

proxy_port[RW]

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

scale[RW]

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

sensor[RW]

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

width[RW]

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

zoom[RW]

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 91
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)}
end

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 157
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("maps.googleapis.com", port)
  http.use_ssl = protocol == 'https'

  resp = http.get2(relative_url(protocol))
  if resp && resp.is_a?(Net::HTTPSuccess)
    if output_file
      File.open(output_file, "wb") {|f| f << resp.body }
    end
    resp.body
  else
    if resp
      raise Exception.new("Error encountered while retrieving google map, code #{resp.code}, text #{resp.body}")
    else
      raise Exception.new("Error while retrieve google map, no response")
    end
  end
end
relative_url(protocol='http') click to toggle source

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

# File lib/googlestaticmap.rb, line 144
def relative_url(protocol='http')
  url(protocol).gsub(/[^\/]*\/\/maps\.googleapis\.com/, "")
end
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 - “maps.googleapis.com/maps/api/staticmap?params…” protocol can be 'http', 'https' or :auto. Specifying :auto will not return

a protocol in the URL ("//maps.googleapis.com/..."), 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 108
def url(protocol='http')
  unless @center || @markers.length > 0 || @paths.length > 0
    raise Exception.new("Need to specify either a center, markers, or a path")
  end
  if !@api_key.nil? && !@client_id.nil?
    rasise Exception.new("You cannot specify both an API key and a client ID, only specify one")
  end
  if !@client_id.nil? && @private_key.nil?
    raise Exception.new("private_key must be specified if using a client ID")
  end
  protocol = 'http' unless protocol == 'http' || protocol == 'https' ||
                           protocol == :auto
  protocol = protocol == :auto ? '' : protocol + ":"
  base = "#{protocol}//maps.googleapis.com"
  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"],
            :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?
  path << attrs.sort_by {|k,v| k}.collect {|attr| "#{attr[0]}=#{attr[1]}"}.join("&")
  if (!@api_key.nil? || !@client_id.nil?) && !@private_key.nil?
    signature = GoogleStaticMapHelpers.sign(path, @private_key)
    path << "&signature=" << signature
  end
  base + path
end