<hr> <div> <spanclass="text">search for nearby places</span> <inputtype="text"id="places-search"placeholder="Ex: 电子科技大学邮政代办所"> <inputtype="button"id="go-places"value="Go"> </div>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//把地点自动完成实例绑定到文本输入框 var timeAutocomplete = new google.maps.places.Autocomplete( document.getElementById('search-within-time-text') ); var zoomAutocomplete = new google.maps.places.Autocomplete( document.getElementById('zoom-to-area-text') ); //添加边界限制为地图范围内 zoomAutocomplete.bindTo('bounds',map); //创建一个文本搜索框 var searchBox = new google.maps.places.SearchBox( document.getElementById('places-search') ); //搜索框范围限制在地图内 searchBox.setBounds(map.getBounds());
//当用户输入一个值时将获得普通查询词条 //用户选择搜索栏提供选项时 functionsearchBoxPlaces(searchBox) { //隐藏上次搜索中的任何地点标记 hideMarkers(placeMarkers); //找到匹配查询词条的所有地点 var places = searchBox.getPlaces(); // For each place, get the icon, name and location. createMarkersForPlaces(places); if (places.length == 0) { window.alert('We did not find any places matching that search!'); } }
// 此函数在用户输入查询词条或位置并点击go按钮时执行 functiontextSearchPlaces() { //捕捉地图界限 var bounds = map.getBounds(); //隐藏上次搜索中的任何地点标记 hideMarkers(placeMarkers); //创建新的地点服务实例 var placesService = new google.maps.places.PlacesService(map); //传入用户输入的查询词条和地图界限 placesService.textSearch({ query: document.getElementById('places-search').value, bounds: bounds }, function(results, status) { //返回的结果(地点数组)状态OK if (status === google.maps.places.PlacesServiceStatus.OK) { createMarkersForPlaces(results); } }); }
// 遍历地点数组并为它们创建标记 functioncreateMarkersForPlaces(places) { var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < places.length; i++) { var place = places[i]; var icon = { url: place.icon, size: new google.maps.Size(35, 35), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(15, 34), scaledSize: new google.maps.Size(25, 25) }; // Create a marker for each place. var marker = new google.maps.Marker({ map: map, icon: icon, title: place.name, position: place.geometry.location, id: place.id }); // If a marker is clicked, do a place details search on it in the next function. marker.addListener('click', function() { getPlacesDetails(this, place); }); //将创建的每个标记放入placeMarkers数组 placeMarkers.push(marker); //调节地图平衡并使它适当放入返回的所有地点标记 if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } } map.fitBounds(bounds); }