Class: Map::MercatorProjection

Inherits:
Object
  • Object
show all
Defined in:
lib/contrek/map/mercator_projection.rb

Defined Under Namespace

Classes: LatLng, Point

Constant Summary collapse

MERCATOR_RANGE =
256

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMercatorProjection

Returns a new instance of MercatorProjection.



21
22
23
24
25
# File 'lib/contrek/map/mercator_projection.rb', line 21

def initialize
  @pixel_origin = Point.new(x: MERCATOR_RANGE / 2, y: MERCATOR_RANGE / 2)
  @pixels_per_lon_degree = MERCATOR_RANGE.to_f / 360
  @pixels_per_lon_radian = MERCATOR_RANGE.to_f / (2 * Math::PI)
end

Class Method Details

.get_corners(center, zoom, map_width, map_height) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/contrek/map/mercator_projection.rb', line 27

def self.get_corners(center, zoom, map_width, map_height)
  scale = 2**zoom
  proj = Map::MercatorProjection.new
  center_px = proj.from_lat_lng_to_point(lat_lng: center)
  sw_point = Point.new(x: center_px.x - ((map_width / 2).to_f / scale), y: center_px.y + ((map_height / 2).to_f / scale))
  sw_lat_lon = proj.from_point_to_lat_lng(sw_point)
  ne_point = Point.new(x: center_px.x + ((map_width / 2).to_f / scale), y: center_px.y - ((map_height / 2).to_f / scale))
  ne_lat_lon = proj.from_point_to_lat_lng(ne_point)
  {
    N: ne_lat_lon.lat,
    E: ne_lat_lon.lng,
    S: sw_lat_lon.lat,
    W: sw_lat_lon.lng
  }
end

Instance Method Details

#from_lat_lng_to_point(lat_lng:, opt_point: nil) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/contrek/map/mercator_projection.rb', line 43

def from_lat_lng_to_point(lat_lng:, opt_point: nil)
  point = opt_point.nil? ? Point.new(x: 0, y: 0) : opt_point
  origin = @pixel_origin
  point.x = origin.x + (lat_lng.lng * @pixels_per_lon_degree)
  siny = bound(Math.sin(degreesToRadians(lat_lng.lat)), -0.9999, 0.9999)
  point.y = origin.y + (0.5 * Math.log((1 + siny) / (1 - siny)) * -@pixels_per_lon_radian)
  point
end

#from_point_to_lat_lng(point) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/contrek/map/mercator_projection.rb', line 52

def from_point_to_lat_lng(point)
  origin = @pixel_origin
  lng = (point.x - origin.x) / @pixels_per_lon_degree
  lat_radians = (point.y - origin.y) / -@pixels_per_lon_radian
  lat = radiansToDegrees(2 * Math.atan(Math.exp(lat_radians)) - (Math::PI / 2))
  LatLng.new(lat: lat, lng: lng)
end