2016-06-10 110 views
0

我使用google api搜索框。如果我插入示例“伦敦酒店”脚本给我很多结果。我如何更改代码以给出结果示例5的确切数量?Google api搜索框结果编号

感谢您ansefer

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

function initAutocomplete() { 
    var map = new google.maps.Map(document.getElementById('map'), { 
     center: {lat: -33.8688, lng: 151.2195}, 
     zoom: 13, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }); 

    // Create the search box and link it to the UI element. 
    var input = document.getElementById('pac-input'); 
    var searchBox = new google.maps.places.SearchBox(input); 
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(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 = []; 

     // For each place, get the icon, name and location. 
     var bounds = new google.maps.LatLngBounds(); 
     places.forEach(function(place) { 
     var icon = { 
      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. 
     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); 
    }); 
    } 

回答

0

而是这样做是为了让所有的地方:

places.forEach(function(place) { 

改变,要一个正常的循环,使用最大5或位置数组的大小,以较小者为准。

for (var i = 0; i < Math.min(places.length, 5); i++) { 
    // and within the loop, refer to each place as 'places[i]' instead of 'place'