Using API to take in address name and convert to latitude/longitude

Hi, I’m unfamiliar with this API, and my method of doing it was manually using the url in Python, doing something as follows:

def longitude_calc(each):
    url = "https://developers.onemap.sg/commonapi/search?searchVal=" + str(each) + "&returnGeom=Y&getAddrDetails=Y&pageNum=1"
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')
    soup_object = soup.prettify()
    
    dict1 = ast.literal_eval(soup_object)
    print(dict1['results'][0]['LONGITUDE'])
    try:
        return dict1['results'][0]['LONGITUDE']

    except(IndexError):
        pass
 
longitudes2 = clusters_info2['actual_location'].apply(longitude_calc)

Right now I have a column of address names. I want to convert this column into different columns that represent Longitude and Latitude, but I don’t quite get how to go about doing this using the API. Tried referring to the documentation but the only sense I could make of it was that the url was used to get the job done.

My function in Python above didn’t seem to work for some reason or another. I used beautifulsoup to manually parse the resulting page. Is there a simpler way to retrieve the latitude/longitude from it?

Hi @blueberrypudding85, our API endpoint data response is already in JSON format. Yet, you are using html parser…

You can just use a simple HTTP get to return as json.


https://www.programcreek.com/python/example/127/urllib2.Request

One of our community has created this python client module for OneMap: Contribution: Python API Client 🔥