geocoder-php / Geocoder

The most featured Geocoder library written in PHP.
https://geocoder-php.org
MIT License
3.95k stars 519 forks source link

[RFC] CacheProvider > Cache ReverseQuery with less precision #882

Closed ruudk closed 6 years ago

ruudk commented 6 years ago

We're using Geocoder and we love it!

Since Google is going to charge a lot of money for their Google Maps api we were looking into ways to reduce our API calls.

We do a lot of reverse queries (lat/long to city/country) and want to cache these queries with less precision. For example 52.3705273, 4.891031 could be cached with a precision of 4 decimals: 52.3705, 4.8910

Our plan is to change the CachePlugin so that it takes a precision parameter in it's constructor. Then update the Symfony bundle to add cache_precision. Then change the getCacheKey to this:

    /**
     * @param Query $query
     *
     * @return string
     */
    private function getCacheKey(Query $query): string
    {
        if ($query instanceof ReverseQuery) {
            $query = $query->withCoordinates(new Coordinates(
                number_format($query->getCoordinates()->getLatitude(), $this->precision),
                number_format($query->getCoordinates()->getLongitude(), $this->precision)
            ));
        }

        // Include the major version number of the geocoder to avoid issues unserializing.
        return 'v4'.sha1((string) $query);
    }

Would this be something you would accept? If so, we create the PR :)

Nyholm commented 6 years ago

I use the HTTPlug's cache plugin to make sure I do not use as many HTTP requests to Google. By introducing some more logic to this CacheProvider will make it more useful. HTTPlug has no change to "trim" the query like this.

Big đź‘Ť