如何使用@react-google-maps/api获取某国家的所有州和城市
使用@react-google-maps/api获取指定国家的州与城市
核心思路
@react-google-maps/api主要用于地图渲染,获取行政区划数据依赖Google Places API的地点检索能力。通过指定地点类型(如administrative_area_level_1对应州/省,locality对应城市)和国家边界限制,即可筛选出目标数据。
实现步骤
1. 安装依赖
确保已安装所需包:
npm install @react-google-maps/api
2. 加载Google Maps API并初始化服务
使用LoadScript组件加载API,同时启用places库以获取地点检索能力:
import { LoadScript, useLoadScript } from '@react-google-maps/api'; const libraries = ['places']; const apiKey = '你的Google Maps API密钥'; // 替换为你的密钥 const MapContainer = () => { const { isLoaded } = useLoadScript({ googleMapsApiKey: apiKey, libraries, }); if (!isLoaded) return <div>加载中...</div>; // 后续逻辑写在这里 return <div></div>; };
3. 获取指定国家的所有州
通过PlacesService的textSearch方法,限定国家代码和地点类型为州级行政区:
import { useCallback } from 'react'; const getStates = useCallback(async (countryCode) => { const service = new window.google.maps.places.PlacesService(document.createElement('div')); const request = { query: `administrative area in ${countryCode}`, type: 'administrative_area_level_1', componentRestrictions: { country: countryCode }, // 国家代码如US、CN }; return new Promise((resolve, reject) => { service.textSearch(request, (results, status) => { if (status === window.google.maps.places.PlacesServiceStatus.OK) { const states = results.map(place => ({ id: place.place_id, name: place.name, location: { lat: place.geometry.location.lat(), lng: place.geometry.location.lng() } })); resolve(states); } else { reject(new Error(`获取州数据失败:${status}`)); } }); }); }, []); // 调用示例:获取美国的州 getStates('US').then(states => console.log('美国各州:', states));
4. 获取指定州下的所有城市
先通过州的place_id获取其地理边界,再基于边界搜索城市级行政区:
const getCitiesByState = useCallback(async (statePlaceId, countryCode) => { const service = new window.google.maps.places.PlacesService(document.createElement('div')); // 获取州的地理边界 const placeDetailsReq = { placeId: statePlaceId, fields: ['geometry'], }; const stateDetails = await new Promise((resolve, reject) => { service.getDetails(placeDetailsReq, (place, status) => { if (status === window.google.maps.places.PlacesServiceStatus.OK) { resolve(place); } else { reject(new Error(`获取州详情失败:${status}`)); } }); }); // 基于州边界搜索城市 const citiesReq = { bounds: stateDetails.geometry.viewport, type: 'locality', componentRestrictions: { country: countryCode }, }; return new Promise((resolve, reject) => { service.nearbySearch(citiesReq, (results, status) => { if (status === window.google.maps.places.PlacesServiceStatus.OK) { const cities = results.map(place => ({ id: place.place_id, name: place.name, location: { lat: place.geometry.location.lat(), lng: place.geometry.location.lng() } })); resolve(cities); } else { reject(new Error(`获取城市数据失败:${status}`)); } }); }); }, []); // 调用示例:传入某州的place_id获取对应城市 getCitiesByState('州的place_id', 'US').then(cities => console.log('该州城市:', cities));
关键注意事项
- API权限配置:确保你的Google Cloud项目已启用
Places API,并为API密钥配置正确的计费与权限规则。 - 请求配额限制:Google Places API有请求次数限制,批量获取数据建议分批次请求。
- 行政区划类型适配:部分国家的行政区划类型可能有差异,需根据目标国家调整
type参数(如部分地区用administrative_area_level_2表示次级行政区)。
内容的提问来源于stack exchange,提问作者xKralTr
相关产品推荐
相关产品推荐

