Method: PlusCodes::OpenLocationCode#encode

Defined in:
lib/plus_codes/open_location_code.rb

#encode(latitude, longitude, code_length = PAIR_CODE_LENGTH) ⇒ String

Converts a latitude and longitude into a Open Location Code(Plus+Codes).

Parameters:

  • latitude (Numeric)

    a latitude in degrees

  • longitude (Numeric)

    a longitude in degrees

  • code_length (Integer) (defaults to: PAIR_CODE_LENGTH)

    the number of characters in the code, this excludes the separator

Returns:

  • (String)

    a plus+codes

Raises:

  • (ArgumentError)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/plus_codes/open_location_code.rb', line 44

def encode(latitude, longitude, code_length = PAIR_CODE_LENGTH)
  raise ArgumentError,
  "Invalid Open Location Code(Plus+Codes) length: #{code_length}" if invalid_length?(code_length)

  latitude = clip_latitude(latitude)
  longitude = normalize_longitude(longitude)
  latitude -= precision_by_length(code_length) if latitude == 90

  lat = (latitude + 90).to_r
  lng = (longitude + 180).to_r

  digit = 0
  code = ''
  while digit < code_length
    lat, lng = narrow_region(digit, lat, lng)
    digit, lat, lng = build_code(digit, code, lat, lng)
    code << SEPARATOR if (digit == SEPARATOR_POSITION)
  end

  digit < SEPARATOR_POSITION ? padded(code) : code
end