j_d*_*j_d 6 javascript jquery google-maps google-maps-api-3
所以我有一个带位置输入的搜索页面.如果用户来自带有搜索查询的其他页面,我想以编程方式将此查询输入到输入中并触发更改的位置.
这是我到目前为止所拥有的:
var searchBox = new google.maps.places.SearchBox(input);
$('input#location').val(searchQuery);
google.maps.event.trigger(searchBox, 'places_changed');
Run Code Online (Sandbox Code Playgroud)
但是,这给了我Cannot read property 'length' of undefined这行places_changed函数的错误:
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
Run Code Online (Sandbox Code Playgroud)
因此,在以编程方式填充输入时,可以清楚地searchBox返回.我怎么能绕过这个?undefinedgetPlaces()
更新: 这是一个JSFiddle来举例说明我的意思.
我们来看看SearchBox的工作流程:
结论:
当您知道searchTerm并且不需要选择预测时,只需跳过步骤1-3并直接运行TextSearch.将返回的数组分配给places-property的位置SearchBox(places_changed-event将自动触发,因为SearchBox是MVCObject,其中将观察属性的更改并自动触发相关事件)
function initialize() {
var goo = google.maps,
map = new goo.Map(document.getElementById('map_canvas'), {
zoom: 1,
center: new goo.LatLng(0, 0),
noClear: true
}),
input = map.getDiv().querySelector('input'),
ac = new goo.places.SearchBox(input),
service = new goo.places.PlacesService(map),
win = new goo.InfoWindow,
markers = [],
request;
map.controls[goo.ControlPosition.TOP_CENTER].push(input);
if (input.value.match(/\S/)) {
request = {
query: input.value
};
if (ac.getBounds()) {
request.bounds = ac.getBounds();
}
service.textSearch(request, function(places) {
//set the places-property of the SearchBox
//places_changed will be triggered automatically
ac.set('places', places || [])
});
}
goo.event.addListener(ac, 'places_changed', function() {
win.close();
//remove previous markers
while (markers.length) {
markers.pop().setMap(null);
}
//add new markers
(function(places) {
var bounds = new goo.LatLngBounds();
for (var p = 0; p < places.length; ++p) {
markers.push((function(place) {
bounds.extend(place.geometry.location);
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
}),
content = document.createElement('div');
content.appendChild(document.createElement('strong'));
content.lastChild.appendChild(document.createTextNode(place.name));
content.appendChild(document.createElement('div'));
content.lastChild.appendChild(document.createTextNode(place.formatted_address));
goo.event.addListener(marker, 'click', function() {
win.setContent(content);
win.open(map, this);
});
return marker;
})(places[p]));
};
if (markers.length) {
if (markers.length === 1) {
map.setCenter(bounds.getCenter());
} else {
map.fitBounds(bounds);
}
}
})(this.getPlaces());
});
}
google.maps.event.addDomListener(window, 'load', initialize);Run Code Online (Sandbox Code Playgroud)
html,
body,
#map_canvas {
height: 100%;
margin: 0;
padding: 0
}
strong{
font-weight:bold;
}Run Code Online (Sandbox Code Playgroud)
<div id="map_canvas">
<input value="berlin">
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>Run Code Online (Sandbox Code Playgroud)