I need to use Google Maps (v3) to check whether an address typed into a search field actually exists and print it out on the screen. That's easy enough to do just by checking whether a latitude/longitude pair is found for that address. However, I have a problem.
When a user types in a broad search, such as a common street name like First Street, I need to print out all the results found so the user can choose one. I do not need to display the results on the map at this point, just show a list of them on the page. I found some code online that is supposed to do just that and I modified it but it doesn't work. I get a 'GClientGeocoder() is not defined' error, but I suspect that even when I get past that the code will have problems so I was wondering if someone with more experience could point me in the right direction.
Here's the code, I hardcoded the search term 'First Street' into the function for testing purposes.
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');
}
}
);
}
"Message" is just a regular <div>
. The function is called from the body tag:
<body onLoad='showAddress()'>
This code is created for the outdated V2-API, I guess you are loading the V3-API-scripts.
When I run it with the V2-API it works fine.
V2 and V3 are not compatible in any way.
Code translated to V3:
function showAddress() {
var geo = new google.maps.Geocoder();
var address = 'First Street';
geo.geocode({"address": address},
function(result,status)
{
var out='no results found';
if (status == google.maps.GeocoderStatus.OK)
{
if(result.length==1)
{
out = "Result found:"+result[0].formatted_address;
}
else
{
out = "Did you mean:";
for(var i=0;i<result.length;++i)
{
out+="<br>"+(i+1)+": "+result[i].formatted_address;
}
}
}
document.getElementById("message").innerHTML = out;
}
);
}