Search code examples
rapigoogle-mapsgeolocationgoogleway

R, googleway, matching address by removing word


If I run the below codes directly, it gives me an error because the address is too specified, however if I remove -272, it works fine.

So how can I keep removing words automatically until the function runs and give me the address,

library(googleway)    
 google_geocode(address = "경북 경주시 외동읍 문산공단길 84-272", language = "kr", key = api_key,

Solution

  • The API works for me if I use the address in your question. However, using the address in your other question gives me a ZERO_RESULTS return.

    We can remove the last part(s) of the address after the final space using simple regex in a gsub() command.

    library(googleway)
    set_key("your_api_key")
    
    ## invalid query
    add <- "대한민국 경기도 안산시 단원구 성곡동 강촌로 140"
    res <- google_geocode(address = add, language = "kr")
    res
    # $results
    # list()
    # 
    # $status
    # [1] "ZERO_RESULTS"
    
    ## remove the last part after the final space and it works
    new_add <- gsub(' \\S*$', '', add)
    
    res <- google_geocode(address = new_add, language = "kr")
    geocode_coordinates(res)
    #        lat      lng
    # 1 37.31737 126.7672
    

    You can convert this into an iterative loop that will continue to remove everything after the final 'space' character and attempt to geocode on the new address.

    ## the curl_proxy argument is optional / specific for this scenario 
    geocode_iterate <- function(address, curl_proxy) {
    
        continue <- TRUE
        iterator <- 1
    
        while (continue) {
            print(paste0("attempt ", iterator))
            print(address)
            iterator <- iterator + 1
    
            res <- google_geocode(address = address, language = "kr", curl_proxy = curl_proxy)
            address <- gsub(' \\S*$', '', address)
    
            if (res[['status']] == "OK" | length(add) == 0 | grepl(" ", add) == FALSE ){
                continue <- FALSE
            }
        }
        return(res)
    }
    
    add <- "대한민국 경기도 안산시 단원구 성곡동 강촌로 140"
    res <- geocode_iterate(address = add, curl_proxy = curl_proxy)
    # [1] "attempt 1"
    # [1] "대한민국 경기도 안산시 단원구 성곡동 강촌로 140"
    # [1] "attempt 2"
    # [1] "대한민국 경기도 안산시 단원구 성곡동 강촌로"
    

    Be careful to make sure the while loop CAN actually exit. You don't want to enter an infinite loop.

    And remember that even though ZERO_RESULTS are returned, the query still counts towards your daily API quota.