By: Shamima Sultana

In reply to Mentor.

Hello Mentor,

You will need to modify the VBA function to return only the city and country from the OpenStreetMap response, update the code as follows:

Adjust the URL to request JSON data instead of XML by adding &format=json. Parse the JSON response to extract only the “city” and “country” fields.
Here’s the updated VBA code:

Option Explicit
Function ReverseGeocode(lati As Double, longi As Double) As String
On Error GoTo ErrorHandler
Dim http As Object, json As Object
Dim URL As String
URL = "https://nominatim.openstreetmap.org/reverse?lat=" & CStr(lati) & _
"&lon=" & CStr(longi) & "&format=json"

' Create and send the HTTP request
Set http = CreateObject("MSXML2.XMLHTTP.6.0")
http.Open "GET", URL, False
http.send

' Parse the JSON response
Set json = JsonConverter.ParseJson(http.responseText)

' Extract city and country
Dim city As String, country As String
city = json("address")("city")
country = json("address")("country")

' Return formatted result
ReverseGeocode = city & ", " & country
Exit Function

ErrorHandler:
ReverseGeocode = "Error: " & Err.Description
End Function

Important Notes:
Ensure that you have a JSON parser installed in VBA (e.g., VBA-JSON).
This code returns only the city and country as requested.

Regards
ExcelDemy