]> git.openstreetmap.org Git - rails.git/blobdiff - app/assets/javascripts/index/directions-endpoint.js
Reverse-geocode when coordinates are passed to endpoint.setValue
[rails.git] / app / assets / javascripts / index / directions-endpoint.js
index 59f0b929d497a14bb2e790d80c2ba5f0aa1d3924..b3d03cdca5ccc97b4a5a9bcfc5119271ad75e91f 100644 (file)
@@ -55,7 +55,7 @@ OSM.DirectionsEndpoint = function Endpoint(map, input, iconUrl, dragCallback, ch
     endpoint.setValue(value);
   }
 
-  endpoint.setValue = function (value, latlng) {
+  endpoint.setValue = function (value) {
     endpoint.value = value;
     removeLatLng();
     input.removeClass("is-invalid");
@@ -64,9 +64,13 @@ OSM.DirectionsEndpoint = function Endpoint(map, input, iconUrl, dragCallback, ch
     if (endpoint.geocodeRequest) endpoint.geocodeRequest.abort();
     delete endpoint.geocodeRequest;
 
+    var coordinatesMatch = value.match(/^\s*([+-]?\d+(?:\.\d*)?)(?:\s+|\s*[/,]\s*)([+-]?\d+(?:\.\d*)?)\s*$/);
+    var latlng = coordinatesMatch && L.latLng(coordinatesMatch[1], coordinatesMatch[2]);
+
     if (latlng) {
       setLatLng(latlng);
       setInputValueFromLatLng(latlng);
+      getReverseGeocode();
       changeCallback();
     } else if (endpoint.value) {
       getGeocode();
@@ -93,6 +97,20 @@ OSM.DirectionsEndpoint = function Endpoint(map, input, iconUrl, dragCallback, ch
     });
   }
 
+  function getReverseGeocode() {
+    var reverseGeocodeUrl = OSM.NOMINATIM_URL + "reverse?lat=" + endpoint.latlng.lat + "&lon=" + endpoint.latlng.lng + "&format=json";
+
+    endpoint.geocodeRequest = $.getJSON(reverseGeocodeUrl, function (json) {
+      delete endpoint.geocodeRequest;
+      if (!json || !json.display_name) {
+        return;
+      }
+
+      endpoint.value = json.display_name;
+      input.val(json.display_name);
+    });
+  }
+
   function setLatLng(ll) {
     input
       .attr("data-lat", ll.lat)