我正在使用自動完成功能進行地圖搜索,其中一旦選擇了新地址,當前標記將被刪除並替換爲用戶搜索的地址。要做到這一點,我使用的是搜索框,但是一些結果顯示在自動完成功能上不起作用,比如「shopping」或「audi」,它會在地圖上爲每個地方的結果添加一個標記。我正試圖將這些結果過濾到地址,但似乎無法使其工作。我不斷地看到文檔中的類型:地址屬性,但似乎無法弄清楚在這種情況下會發生什麼。任何幫助真正感謝!這裏是我的代碼:使用Google Places搜索框來檢索僅地址結果
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('gmap_canvas'), {
zoom: 14,
center: new google.maps.LatLng(39.711383, -105.018230),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
streetViewControl: true,
mapTypeControl: false
});
var myLatLng = {lat: 39.711383, lng: -105.018230};
var icon = {
url: "../../../images/gold-delivery-128.png",
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(64, 64)
};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: icon
});
// Create the search box and link it to the UI element.
var input = document.getElementById('locationTextField');
var searchBox = new google.maps.places.SearchBox(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
marker.setVisible(false);
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: "../../../images/gold-delivery-128.png",
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(64, 64)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
謝謝!使用自動完成而不是搜索框取得了訣竅,並允許我使用地理編碼過濾結果。 –