package main import ( "encoding/json" "fmt" "net/http" "net/url" "time" ) type NominatimResponse struct { Lat string `json:"lat"` Lon string `json:"lon"` } func geocodeQuery(query string) (latitude, longitude string, found bool, err error) { // First, check if the result is in the cache cachedLat, cachedLon, cachedFound, exists := geocodeCache.Get(query) if exists { printDebug("Geocode cache hit for query: %s", query) return cachedLat, cachedLon, cachedFound, nil } printDebug("Geocode cache miss for query: %s", query) // URL encode the query queryEscaped := url.QueryEscape(query) // Construct the request URL urlString := fmt.Sprintf("https://nominatim.openstreetmap.org/search?format=json&q=%s", queryEscaped) // Make the HTTP GET request resp, err := http.Get(urlString) if err != nil { return "", "", false, err } defer resp.Body.Close() // Read the response var result []NominatimResponse if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { return "", "", false, err } // Check if there are any results if len(result) > 0 { latitude = result[0].Lat longitude = result[0].Lon found = true } else { found = false } // Store the result in the cache geocodeCache.Set(query, latitude, longitude, found) return latitude, longitude, found, nil } func handleMapSearch(w http.ResponseWriter, settings UserSettings, query string) { // Start measuring the time for geocoding the query startTime := time.Now() // Geocode the query to get coordinates latitude, longitude, found, err := geocodeQuery(query) if err != nil { printDebug("Error geocoding query: %s, error: %v", query, err) http.Error(w, Translate("internal_server_error"), http.StatusInternalServerError) return } // Measure the elapsed time for geocoding elapsedTime := time.Since(startTime) // Prepare the data to pass to the template data := map[string]interface{}{ "Query": query, "Latitude": latitude, "Longitude": longitude, "Found": found, "Fetched": fmt.Sprintf("%.2f %s", elapsedTime.Seconds(), Translate("seconds")), "Theme": settings.Theme, "Safe": settings.SafeSearch, "IsThemeDark": settings.IsThemeDark, } // Render the template renderTemplate(w, "map.html", data) }