2016-06-10 2 views
0

Google 검색 상자를 사용합니다. 예를 들어 "London Hotel"스크립트를 삽입하면 많은 결과를 얻을 수 있습니다. 정확한 결과 수 5를 제공하기 위해 코드를 어떻게 바꿀 수 있습니까? 최대를 사용하여,Google api 검색 상자 결과 번호

places.forEach(function(place) { 

변경하는 루프에 대한 정상 :

대신 모든 장소를 얻기 위해이 일을 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

주셔서 감사합니다 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'