Skip to content

Commit

Permalink
Cache last reverse geocoding result
Browse files Browse the repository at this point in the history
Otherwise selecting "Directions from here" and then "Directions to here" results in two reverse-geocoding request for the starting point.
  • Loading branch information
AntonKhorev committed Aug 12, 2024
1 parent 86e0990 commit 16c5f05
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions app/assets/javascripts/index/directions-endpoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,25 @@ OSM.DirectionsEndpoint = function Endpoint(map, input, iconUrl, dragCallback, ch
});

endpoint.setValue = function (value) {
endpoint.value = value;
removeLatLng();
input.removeClass("is-invalid");
input.val(value);

if (endpoint.geocodeRequest) endpoint.geocodeRequest.abort();
delete endpoint.geocodeRequest;
input.removeClass("is-invalid");

var coordinatesMatch = value.match(/^\s*([+-]?\d+(?:\.\d*)?)(?:\s+|\s*[/,]\s*)([+-]?\d+(?:\.\d*)?)\s*$/);
var latlng = coordinatesMatch && L.latLng(coordinatesMatch[1], coordinatesMatch[2]);

if (latlng && endpoint.cachedReverseGeocode && endpoint.cachedReverseGeocode.latlng.equals(latlng)) {
setLatLng(latlng);
endpoint.value = endpoint.cachedReverseGeocode.value;
input.val(endpoint.value);
changeCallback();
return;
}

endpoint.value = value;
removeLatLng();
input.val(value);

if (latlng) {
setLatLng(latlng);
setInputValueFromLatLng(latlng);
Expand All @@ -73,14 +81,16 @@ OSM.DirectionsEndpoint = function Endpoint(map, input, iconUrl, dragCallback, ch

setLatLng(L.latLng(json[0]));

endpoint.value = json[0].display_name;
input.val(json[0].display_name);

changeCallback();
});
}

function getReverseGeocode() {
var reverseGeocodeUrl = OSM.NOMINATIM_URL + "reverse?lat=" + endpoint.latlng.lat + "&lon=" + endpoint.latlng.lng + "&format=json";
var latlng = endpoint.latlng.clone();
var reverseGeocodeUrl = OSM.NOMINATIM_URL + "reverse?lat=" + latlng.lat + "&lon=" + latlng.lng + "&format=json";

endpoint.geocodeRequest = $.getJSON(reverseGeocodeUrl, function (json) {
delete endpoint.geocodeRequest;
Expand All @@ -92,6 +102,7 @@ OSM.DirectionsEndpoint = function Endpoint(map, input, iconUrl, dragCallback, ch

endpoint.value = json.display_name;
input.val(json.display_name);
endpoint.cachedReverseGeocode = { latlng: latlng, value: endpoint.value };
});
}

Expand Down

0 comments on commit 16c5f05

Please sign in to comment.