我需要使用 Google Maps (v3) 检查输入到搜索字段中的地址是否确实存在并将其打印在屏幕上。只需检查是否为该地址找到了纬度/经度对,就很容易做到这一点。但是,我有一个问题。
当用户输入一个广泛的搜索,例如像第一街这样的常见街道名称时,我需要打印出所有找到的结果,以便用户可以选择一个。此时我不需要在地图上显示结果,只需在页面上显示它们的列表即可。我在网上找到了一些应该这样做的代码,我对其进行了修改,但它不起作用。我收到“未定义 GClientGeocoder()”错误,但我怀疑即使我通过代码也会出现问题,所以我想知道是否有更多经验的人可以为我指明正确的方向。
这是代码,我将搜索词“第一街”硬编码到函数中以进行测试。
function showAddress() {
var geo;
geo = new GClientGeocoder();
var search = 'First Street';
// ====== Perform the Geocoding ======
geo.getLocations(search, function (result)
{
//map.clearOverlays();
if (result.Status.code == G_GEO_SUCCESS) {
// ===== If there was more than one result, "ask did you mean" on them all =====
if (result.Placemark.length > 1) {
document.getElementById("message").innerHTML = "Did you mean:";
// Loop through the results
for (var i=0; i<result.Placemark.length; i++) {
document.getElementById("message").innerHTML += "<br>"+(i+1)+": "+result.Placemark[i].address;
}
}
// ===== If there was a single marker =====
else {
document.getElementById("message").innerHTML = "Result found:"+result.Placemark[0].address;
}
}
// ====== Decode the error status ======
else {
alert('No results found');
}
}
);
}
“消息”只是一个普通的<div>
. 该函数是从 body 标签调用的:
<body onLoad='showAddress()'>