@@ -249,25 +249,34 @@ def encode(latitude, longitude, codeLength=PAIR_CODE_LENGTH_):
249249 raise ValueError ('Invalid Open Location Code length - ' +
250250 str (codeLength ))
251251 codeLength = min (codeLength , MAX_DIGIT_COUNT_ )
252- # Ensure that latitude and longitude are valid.
253- latitude = clipLatitude (latitude )
254- longitude = normalizeLongitude (longitude )
255- # Latitude 90 needs to be adjusted to be just less, so the returned code
256- # can also be decoded.
257- if latitude == 90 :
258- latitude = latitude - computeLatitudePrecision (codeLength )
259- code = ''
260252
261253 # Compute the code.
262- # This approach converts each value to an integer after multiplying it by
263- # the final precision. This allows us to use only integer operations, so
264- # avoiding any accumulation of floating point representation errors.
254+ # This approach converts latitude and longitude to integers. This allows us
255+ # to use only integer operations, so avoiding any accumulation of floating
256+ # point representation errors.
265257
266258 # Multiply values by their precision and convert to positive.
267259 # Force to integers so the division operations will have integer results.
268260 # Note: Python requires rounding before truncating to ensure precision!
269- latVal = int (round ((latitude + LATITUDE_MAX_ ) * FINAL_LAT_PRECISION_ , 6 ))
270- lngVal = int (round ((longitude + LONGITUDE_MAX_ ) * FINAL_LNG_PRECISION_ , 6 ))
261+ latVal = int (round (latitude * FINAL_LAT_PRECISION_ ))
262+ latVal += LATITUDE_MAX_ * FINAL_LAT_PRECISION_
263+ if latVal < 0 :
264+ latVal = 0
265+ elif latVal >= 2 * LATITUDE_MAX_ * FINAL_LAT_PRECISION_ :
266+ latVal = 2 * LATITUDE_MAX_ * FINAL_LAT_PRECISION_ - 1
267+
268+ lngVal = int (round (longitude * FINAL_LNG_PRECISION_ ))
269+ lngVal += LONGITUDE_MAX_ * FINAL_LNG_PRECISION_
270+ if lngVal < 0 :
271+ # Python's % operator differs from other languages in that it returns
272+ # the same sign as the divisor. This means we don't need to add the
273+ # range to the result.
274+ lngVal = lngVal % (2 * LONGITUDE_MAX_ * FINAL_LNG_PRECISION_ )
275+ elif lngVal >= 2 * LONGITUDE_MAX_ * FINAL_LNG_PRECISION_ :
276+ lngVal = lngVal % (2 * LONGITUDE_MAX_ * FINAL_LNG_PRECISION_ )
277+
278+ # Initialise the code string.
279+ code = ''
271280
272281 # Compute the grid part of the code if necessary.
273282 if codeLength > PAIR_CODE_LENGTH_ :
0 commit comments