如何在Google Geocode循环中跳过重复国家以减少API调用
Solution to Avoid Duplicate Google API Calls for Geocoding
Got it! Let's tweak your code to skip duplicate country names and save those valuable Google API calls. We'll add an if check plus a simple cache to store coordinates we've already fetched:
Modified Code
register_google(key='your key') t<-data.frame(importer_country=c("spain", "spain", "spain","united states","spain","eswatini", "spain", "spain", "spain", "spain", "spain", "spain", "spain")) t$importer_country<-as.character(t$importer_country) # Initialize latitude and longitude columns with NA to ensure consistent data types t$importer_lon <- NA_real_ t$importer_lat <- NA_real_ # Create a cache to store coordinates for countries we've already processed coord_cache <- list() for(i in 1:nrow(t)){ current_country <- t$importer_country[i] # Check if we already have coordinates for this country in the cache if(current_country %in% names(coord_cache)){ # Reuse cached coordinates instead of calling the API again t$importer_lon[i] <- coord_cache[[current_country]]$lon t$importer_lat[i] <- coord_cache[[current_country]]$lat } else { # Only call the API for new, unprocessed countries result <- geocode(current_country, output = "latlon", source = "google") t$importer_lon[i] <- as.numeric(result$lon) t$importer_lat[i] <- as.numeric(result$lat) # Save the fetched coordinates to the cache for future use coord_cache[[current_country]] <- list(lon = t$importer_lon[i], lat = t$importer_lat[i]) } } head(t)
Key Changes Explained
- Pre-initialize Columns: We set up
importer_lonandimporter_latwithNA_real_upfront to avoid unexpected data type issues later. - Coordinate Cache: The
coord_cachelist acts as a temporary storage for already retrieved coordinates, mapped by country name. This cuts down API calls from 13 to just 3 (one per unique country). - If Check Logic: Inside the loop, we first verify if the current country exists in our cache. If it does, we pull the stored coordinates; if not, we call the API and immediately save the result to the cache for future duplicates.
This approach keeps your script efficient, stays within Google's API limits, and ensures all duplicate rows get the correct coordinates without redundant calls.
内容的提问来源于stack exchange,提问作者Dr. Flow
相关产品推荐
相关产品推荐

