The page here demonstrates the method. It contains an input element, button and a map. Type something in the field and press search.
Step 1: Initialize the map
var mapHolder = document.getElementById("map-holder");
map = new google.maps.Map(
mapHolder,
{
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
);
map.setCenter(new google.maps.LatLng(43.229195, 27.872314));
Step 2: Calling the method
I simply attached a listener to the onclick event of the button. The addressToLocation function accepts the address (as plain text) and a callback function which will operate with the results.
document.getElementById("search").onclick = function() {
var address = document.getElementById("text").value;
log("Address: " + address, true);
addressToLocation(address, changeMapLocation);
}
Step 3: Create google.maps.LatLng object based on the field's value
The method uses the google.maps.Geocoder object of the GoogleMaps API. At the end it sends the results to the callback function.
function addressToLocation(address, callback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
address: address
},
function(results, status) {
var resultLocations = [];
if(status == google.maps.GeocoderStatus.OK) {
if(results) {
var numOfResults = results.length;
for(var i=0; i<numOfResults; i++) {
var result = results[i];
resultLocations.push(
{
text:result.formatted_address,
addressStr:result.formatted_address,
location:result.geometry.location
}
);
};
}
} else if(status == google.maps.GeocoderStatus.ZERO_RESULTS) {
// address not found
}
if(resultLocations.length > 0) {
callback(resultLocations);
} else {
callback(null);
}
}
);
}
Step 4: Process the results
The callback function accepts only one parameter. It is actually an array of objects. Every object has three properties:
{
text:...(String),
addressStr:...(String),
location:...(google.maps.LatLng)
}
The function outputs all the locations in a div container, pans the map and adds markers for every item in the array.
function changeMapLocation(locations) {
if(locations && locations.length) {
log("Num of results: " + locations.length);
var numOfLocations = locations.length;
for(var i=0; i<numOfLocations; i++) {
log("- " + locations[i].text + " / <strong>" + locations[i].location.toString() + "</strong>");
var marker = new google.maps.Marker({
map: map,
position: locations[i].location
});
}
map.panTo(locations[0].location);
map.setZoom(8);
} else {
log("Num of results: 0");
}
}
The full source code is available here.