如何修正Google Geocoder请求以获取加拿大Camden的正确结果?
问题描述
- 加载Google Maps API的方式:
<script defer src="https://maps.googleapis.com/maps/api/js?v=weekly&callback=initializeMaps®ion=CA&key=*****" type="application/javascript"></script> - 原v=3.4版本正常,切换到v=weekly后,调用Geocoder API搜索
"camden, kent county, Ontario, Canada"返回错误结果(加拿大安大略省全境、美国特拉华州Camden、加拿大新不伦瑞克省肯特县),但网页版Google Maps搜索该字符串可得到正确的镇区边界结果。 - 当前Geocoder调用代码:
geocoder.geocode({ 'address': searchName}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results.length > 1) { alert("Location.js: geocoder returned multiple results for '" + searchName + " : " + JSON.stringify(results)); displayMap(results[1].geometry.location, zoom, searchName); } else displayMap(results[0].geometry.location, zoom, searchName);
解决方案
1. 添加精准的组件限制参数
仅靠region=CA的区域偏好不足以锁定目标地址,直接用componentRestrictions强制限定国家、省份等维度,避免同名地点干扰:
geocoder.geocode({ 'address': searchName, 'componentRestrictions': { 'country': 'CA', 'administrativeArea': 'ON', 'locality': 'Camden' } }, function(results, status) { // 原有回调逻辑不变 });
2. 按结果类型筛选有效条目
网页版返回的镇区边界对应Geocoder结果的types字段会包含administrative_area_level_3或locality,通过过滤该字段排除错误结果:
if (status == google.maps.GeocoderStatus.OK) { const validResults = results.filter(result => result.types.includes('administrative_area_level_3') || result.types.includes('locality') ); if (validResults.length > 0) { displayMap(validResults[0].geometry.location, zoom, searchName); } else { alert("未找到匹配的目标区域"); } }
3. 避免依赖固定索引获取结果
API返回结果的顺序可能随版本更新变化,不要硬编码results[1]这类固定索引,始终通过类型或地址匹配度筛选目标结果。
4. 可选:添加边界范围缩小搜索
若知道目标区域的大致经纬度范围,可通过bounds参数进一步限定搜索范围:
const kentCountyBounds = new google.maps.LatLngBounds( new google.maps.LatLng(42.0, -83.0), // 西南角大致坐标 new google.maps.LatLng(43.0, -82.0) // 东北角大致坐标 ); geocoder.geocode({ 'address': searchName, 'componentRestrictions': { 'country': 'CA' }, 'bounds': kentCountyBounds }, function(results, status) { // 原有回调逻辑不变 });
内容的提问来源于stack exchange,提问作者James Cobban
相关产品推荐
相关产品推荐

