Loss of accuracy when parsing Google Maps API data in PHP

Issues with the json_decode function when parsing fractional numbers in PHP

I recently came across a rather subtle and nasty bug when using PHP to parse the responses from the Google Elevation API.

Example response from Google Elevation API

   "elevation" : 1701.672119140625,
   "location" : {
      "lat" : 39.72886619204346,
      "lng" : -105.1162936849545
   "resolution" : 4.771975994110107

The same response data after being parsed by json_decode

   "elevation" : 1701.6721191406,
   "location" : {
      "lat" : 39.728866192043,
      "lng" : -105.11629368495
   "resolution" : 4.7719759941101

I couldn't figure out why the data I observed when debugging the PHP code did not match up to the data I saw when I called the Elevation API directly.

When cross referencing values from the Elevation API I could never find the corresponding data on the PHP side. However when I searched the other way around I could only ever find partial matches to any of the numerical data. This was especially troubling as I am dealing with high precision GPS data and loss of fractions can sometimes mean a loss of hundreds of meters in precision.

I finally tracked the problem to my use of the json_decode function when I was parsing the raw API data. Apparently this function has a known precision-error when parsing fractional numbers.

The function only retrieves the first 10 decimal numbers and simply chops off the rest, which means that


will be parsed as


Notice the loss of the two last fractional digits

This has luckily been resolved and is available as of PHP v7.0 which introduced a new option for the function JSON_PRESERVE_FRACTIONAL_PART.

json_decode($json_data, true, 512, JSON_PRESERVE_FRACTIONAL_PART)

Unfortunately this does little for those still stuck on older versions of PHP. Unfortunately Google does not offer client libraries for PHP. So if those extra decimal points matter then you should seriously consider using a third party library.

Software Developer
Contact Me

Developer & Programmer with +18 years professional experience building software.