You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python结合Google Place API批量读取CSV坐标查询医院?

Got it, let's fix this batch processing issue and make your code way more efficient. Here's a step-by-step solution that reads your CSV, processes each coordinate pair, and handles edge cases to keep things running smoothly:

Step 1: Refactor to Read Your CSV File

First, we'll use Python's built-in csv module to parse your input CSV. Your lines follow a format like 1: Hanoi,10.762622,106.660172, so we'll split each entry to extract the city name, latitude, and longitude cleanly.

Step 2: Encapsulate API Logic into a Reusable Function

Instead of repeating API call code, wrap it in a function that accepts coordinates, radius, and keyword as parameters. This makes it trivial to loop through every row in your CSV.

Step 3: Add Efficiency & Error Handling

To avoid hitting Google's API rate limits and handle failures gracefully, we'll add:

  • Request delays to comply with API rules
  • Pagination support to fetch all results (not just the first 20)
  • Try/except blocks to catch network errors or quota issues

Full Updated Code

import urllib.request
import urllib.parse
import json
import csv
import time

def fetch_hospitals(lat, lng, radius=5000, keyword="hospital", api_key="YOUR_API_KEY"):
    """Fetch all hospitals near a given coordinate using Google Place Text Search API"""
    hospitals = []
    base_url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
    page_token = None

    while True:
        # Build request parameters safely
        params = {
            "query": keyword,
            "location": f"{lat},{lng}",
            "radius": radius,
            "key": api_key
        }
        if page_token:
            params["pagetoken"] = page_token
        
        # Encode parameters and construct URL
        encoded_params = urllib.parse.urlencode(params)
        url = f"{base_url}?{encoded_params}"
        
        try:
            response = urllib.request.urlopen(url)
            data = json.loads(response.read().decode('utf-8'))
            
            # Add results to our list
            hospitals.extend(data.get("results", []))
            
            # Check for next page of results
            page_token = data.get("next_page_token")
            if not page_token:
                break
            
            # Wait 2 seconds before next page (required by Google's API terms)
            time.sleep(2)
        
        except Exception as e:
            print(f"Error fetching data for {lat},{lng}: {str(e)}")
            break
    
    return hospitals

def main(input_csv_path, output_csv_path, api_key):
    # Open output file and write header row
    with open(output_csv_path, "w", newline="", encoding="utf-8") as outfile:
        writer = csv.writer(outfile)
        writer.writerow(["City", "Hospital Name", "Latitude", "Longitude"])
        
        # Read and process each line in the input CSV
        with open(input_csv_path, "r", encoding="utf-8") as infile:
            for line_num, line in enumerate(infile, 1):
                line = line.strip()
                if not line:
                    continue
                
                # Split line into parts (handle format: "1: Hanoi,10.762622,106.660172")
                parts = line.split(",")
                if len(parts) < 3:
                    print(f"Skipping invalid line {line_num}: {line}")
                    continue
                
                # Extract city name, latitude, longitude
                city_part = parts[0].split(": ")[1]
                lat = parts[1].strip()
                lng = parts[2].strip()
                
                print(f"Processing {city_part} ({lat}, {lng})...")
                hospitals = fetch_hospitals(lat, lng, api_key=api_key)
                
                # Write each hospital to the output CSV
                for hospital in hospitals:
                    name = hospital.get("name", "")
                    hospital_lat = hospital["geometry"]["location"]["lat"]
                    hospital_lng = hospital["geometry"]["location"]["lng"]
                    writer.writerow([city_part, name, hospital_lat, hospital_lng])
                
                # Add delay between coordinate requests to avoid rate limiting
                time.sleep(1)

if __name__ == "__main__":
    # Replace these with your actual values
    INPUT_CSV = "your_coordinates.csv"
    OUTPUT_CSV = "hospitals.csv"  # Fixed the typo from "hopital" to "hospitals"
    API_KEY = "YOUR_GOOGLE_API_KEY"
    
    main(INPUT_CSV, OUTPUT_CSV, API_KEY)

Key Improvements & Efficiency Tips

  • Batch Automation: Reads every coordinate from your CSV automatically—no more manual edits.
  • Full Result Set: Uses next_page_token to fetch all available hospitals, not just the first 20.
  • Rate Limit Protection: Adds required delays between page requests and coordinate calls to stay within Google's API rules.
  • Robust Error Handling: Catches network issues and invalid lines, so your script won't crash halfway through processing.
  • Proper CSV Handling: Uses the csv module to avoid issues with commas in hospital names or non-ASCII characters (like Vietnamese city names).
  • Clean, Maintainable Code: Encapsulates repeated logic into functions, making it easy to modify later (e.g., switch to "clinic" instead of "hospital").

Optional Extra Efficiency Boosts

  • Asynchronous Requests: For large CSV files, use aiohttp to make concurrent requests (just be careful not to exceed your Google API quota limits).
  • Caching: Add a cache (like a JSON file) to store results for coordinates you've already processed, avoiding redundant API calls if you re-run the script.
  • Quota Monitoring: Add code to check your API quota usage mid-script to avoid unexpected shutdowns.

内容的提问来源于stack exchange,提问作者Simon GIS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:47:59