I have a simple search feature on my website and I'm attempting to access the address_components of the place result object. But it's always undefined.
Essentially what I'm try to retrieve is the postcode for displaying in the infowindow for each marker. I've previously used formatted_address for each place but it doesn't contain the postcode. I'm assuming that either long_name or short_name may contain the postcode but I don't know how to retrieve it.
This is the code I have so far:
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('admin-map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var vges = new google.maps.LatLng(x, y);
var defaultBounds = new google.maps.Circle({center: vges, radius: 2000}).getBounds();
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** @type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** @type {HTMLInputElement} */(input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
var infowindow = new google.maps.InfoWindow({
content:"",
maxWidth: 300
});
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
if(typeof place.address_components=='undefined'){
address= "foo";
}
else{
address= place.address_components[0];
}
markers.push(marker);
bindInfoWindow(marker,map,infowindow,place.name,address);
bounds.extend(place.geometry.location);
}
function bindInfoWindow(marker,map,InfoWindow,strDescription,Address){
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(strDescription + ", " + Address);
infowindow.open(map,marker);
});
}
map.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
$(document).ready(function(){
google.maps.event.addDomListener(window, 'load', initialize);
});