diff options
author | Anton Tananaev <anton.tananaev@gmail.com> | 2015-09-21 10:07:27 +1200 |
---|---|---|
committer | Anton Tananaev <anton.tananaev@gmail.com> | 2015-09-21 10:07:27 +1200 |
commit | 87f6ffa67c2cd4b3e7ce72ed7257ea15526c0052 (patch) | |
tree | 0ed5252d622cdc0ae6d71306ee70afa539de3c9c /src/org/traccar/geocode/JsonReverseGeocoder.java | |
parent | ccaea63b14e67ae97bef2a0c826337dc3fa4e509 (diff) | |
download | trackermap-server-87f6ffa67c2cd4b3e7ce72ed7257ea15526c0052.tar.gz trackermap-server-87f6ffa67c2cd4b3e7ce72ed7257ea15526c0052.tar.bz2 trackermap-server-87f6ffa67c2cd4b3e7ce72ed7257ea15526c0052.zip |
Implement geocoder address caching
Diffstat (limited to 'src/org/traccar/geocode/JsonReverseGeocoder.java')
-rw-r--r-- | src/org/traccar/geocode/JsonReverseGeocoder.java | 29 |
1 files changed, 27 insertions, 2 deletions
diff --git a/src/org/traccar/geocode/JsonReverseGeocoder.java b/src/org/traccar/geocode/JsonReverseGeocoder.java index c43641245..442b8551c 100644 --- a/src/org/traccar/geocode/JsonReverseGeocoder.java +++ b/src/org/traccar/geocode/JsonReverseGeocoder.java @@ -25,18 +25,37 @@ import java.io.Reader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; +import java.util.AbstractMap; +import java.util.LinkedHashMap; +import java.util.Map; public abstract class JsonReverseGeocoder implements ReverseGeocoder { private final String url; - public JsonReverseGeocoder(String url) { + private Map<Map.Entry<Double, Double>, String> cache; + + public JsonReverseGeocoder(String url, final int cacheSize) { this.url = url; + if (cacheSize > 0) { + this.cache = new LinkedHashMap<Map.Entry<Double, Double>, String>() { + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > cacheSize; + } + }; + } } @Override public String getAddress(AddressFormat format, double latitude, double longitude) { + if (cache != null) { + String cachedAddress = cache.get(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude)); + if (cachedAddress != null) { + return cachedAddress; + } + } + try { HttpURLConnection conn = (HttpURLConnection) new URL(String.format(url, latitude, longitude)).openConnection(); conn.setRequestProperty("Connection", "close"); // don't keep-alive connections @@ -46,7 +65,13 @@ public abstract class JsonReverseGeocoder implements ReverseGeocoder { Address address = parseAddress(reader.readObject()); while (streamReader.read() > 0); // make sure we reached the end if (address != null) { - return format.format(address); + String formattedAddress = format.format(address); + + if (cache != null) { + cache.put(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude), formattedAddress); + } + + return formattedAddress; } } } finally { |