Skip to content

Commit fe62798

Browse files
authored
Modify integer conversion for Java library (#689)
* update java encoding * remove comments
1 parent 4c2ff8a commit fe62798

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

java/src/main/java/com/google/openlocationcode/OpenLocationCode.java

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -194,14 +194,6 @@ public OpenLocationCode(double latitude, double longitude, int codeLength) {
194194
if (codeLength < PAIR_CODE_LENGTH && codeLength % 2 == 1 || codeLength < MIN_DIGIT_COUNT) {
195195
throw new IllegalArgumentException("Illegal code length " + codeLength);
196196
}
197-
// Ensure that latitude and longitude are valid.
198-
latitude = clipLatitude(latitude);
199-
longitude = normalizeLongitude(longitude);
200-
201-
// Latitude 90 needs to be adjusted to be just less, so the returned code can also be decoded.
202-
if (latitude == LATITUDE_MAX) {
203-
latitude = latitude - 0.9 * computeLatitudePrecision(codeLength);
204-
}
205197

206198
// Store the code - we build it in reverse and reorder it afterwards.
207199
StringBuilder revCodeBuilder = new StringBuilder();
@@ -211,12 +203,24 @@ public OpenLocationCode(double latitude, double longitude, int codeLength) {
211203
// the final precision. This allows us to use only integer operations, so
212204
// avoiding any accumulation of floating point representation errors.
213205

214-
// Multiply values by their precision and convert to positive. Rounding
215-
// avoids/minimises errors due to floating point precision.
216-
long latVal =
217-
(long) (Math.round((latitude + LATITUDE_MAX) * LAT_INTEGER_MULTIPLIER * 1e6) / 1e6);
218-
long lngVal =
219-
(long) (Math.round((longitude + LONGITUDE_MAX) * LNG_INTEGER_MULTIPLIER * 1e6) / 1e6);
206+
long latVal = (long) Math.round(latitude * LAT_INTEGER_MULTIPLIER);
207+
long lngVal = (long) Math.round(longitude * LNG_INTEGER_MULTIPLIER);
208+
209+
// Clip and normalise values.
210+
latVal += LATITUDE_MAX * LAT_INTEGER_MULTIPLIER;
211+
if (latVal < 0) {
212+
latVal = 0;
213+
} else if (latVal >= 2 * LATITUDE_MAX * LAT_INTEGER_MULTIPLIER) {
214+
latVal = 2 * LATITUDE_MAX * LAT_INTEGER_MULTIPLIER - 1;
215+
}
216+
lngVal += LONGITUDE_MAX * LNG_INTEGER_MULTIPLIER;
217+
if (lngVal < 0) {
218+
lngVal =
219+
lngVal % (2 * LONGITUDE_MAX * LNG_INTEGER_MULTIPLIER)
220+
+ 2 * LONGITUDE_MAX * LNG_INTEGER_MULTIPLIER;
221+
} else if (lngVal >= 2 * LONGITUDE_MAX * LNG_INTEGER_MULTIPLIER) {
222+
lngVal = lngVal % (2 * LONGITUDE_MAX * LNG_INTEGER_MULTIPLIER);
223+
}
220224

221225
// Compute the grid part of the code if necessary.
222226
if (codeLength > PAIR_CODE_LENGTH) {

0 commit comments

Comments
 (0)