Gem provides a way to calculate zoom level using boudary, and project map to viewports(html elements) 0.0.3 Update: Fix rounding issue when viewport smaller than 256px

gem install map_project -v 0.0.3



This gem provides a set of tools which can help users to map geo lat-lng to viewport coords. For example, you can use this gem to convert lat-long points to html <div> coords.

This gem applies to many user cases, for example, when:

  • You have a set of lat,long positions, and want to drop them as pins on map
  • You have a map, and want to sprite it in to multiple viewports
  • You need the actual on-map boundary
  • You need mapping between lat,long and google world, google pixel coords.
  • ...


In Gemfile:

gem 'map_project'

and bundle:

$ bundle install

Then, include:

include MapProject

In any files you need.


If you have a boundary:

{sw: [MIN_LAT, MIN_LNG],
 ne: [MAX_LAT, MAX_LNG]})

and you know your viewport sizes (ex. width and height of a <div>), you can get the zoom level:

zoom_level = get_bounds_zoom_level(boundary, viewport_width, viewport_height)

Once you get the zoom level, you can do a lot of more:
First, create a map_project object:

map_projection ={zoom_level: ZOOMLEVEL, lat: LAT, long: LONG, viewport_w: VIEWPORT_WIDTH, viewport_h: VIEWPORT_HEIGHT})

The :lat and :long are the geo position of the center. Example:

map_projection ={zoom_level: 15, lat: 37.294742, long: -122.019252, viewport_w: 1024, viewport_h: 1024})

Then, you can:
Convert geo lat-lng to Google World Coords:


Convert geo lat-lng to Google Pixel Coords:


Get number of pixels per latitude/longitude inside this map area:


Map any geo lat-lng points to viewport coords:

(0,0)         (0, x)
     |          |
     | viewport |
     |          |
(y, 0)        (x, y)
map_project.offset_on_viewport(input_lat, input_long)

Get pixel boundary on this viewport:


The input boundary you used for getting zoom level may be different from the real boundary on map. Get actual geo boundary on this viewport: