【发布时间】:2014-01-17 20:09:36
【问题描述】:
我的网站上有一个简单的搜索功能,我正在尝试访问地点结果对象的 address_components。但它总是不确定的。
基本上我要检索的是用于在信息窗口中显示每个标记的邮政编码。我以前对每个地方都使用了 formatted_address,但它不包含邮政编码。我假设 long_name 或 short_name 可能包含邮政编码,但我不知道如何检索它。
这是我到目前为止的代码:
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);
});
【问题讨论】:
标签: javascript google-maps google-maps-api-3