As avaliações de lugares permitem adicionar avaliações e classificações de usuários às suas páginas da Web. Esta página
explica as diferenças entre as avaliações de lugares usadas na classe Place
(nova) e PlacesService (legado) e oferece alguns snippets de código para
comparação.
PlacesService(legado) retorna uma matriz de instânciasPlaceReviewcomo parte do objetoPlaceResultpara qualquer solicitaçãogetDetails()se o camporeviewsfor especificado na solicitação.Place(novo) retorna uma matriz de instânciasReviewcomo parte de uma solicitaçãofetchFields()se o camporeviewsfor especificado na solicitação.
A tabela a seguir lista algumas das principais diferenças no uso de avaliações de lugares entre a classe Place e PlacesService:
PlacesService (legado) |
Place (novo) |
|---|---|
PlaceReview interface |
Review classe |
Os métodos exigem o uso de um callback para processar o objeto de resultados e
google.maps.places.PlacesServiceStatus resposta. |
Usa Promises e funciona de forma assíncrona. |
Os métodos exigem uma verificação de PlacesServiceStatus. |
Nenhuma verificação de status necessária, pode usar o tratamento de erros padrão. Saiba mais. |
PlacesService precisa ser instanciado usando um mapa ou um
elemento div. |
Place pode ser instanciado onde for necessário, sem uma
referência a um mapa ou elemento de página. |
PlaceReview retorna dados de atribuição para a avaliação usando
os campos author_name, author_url e
profile_photo_url. |
Review retorna dados de atribuição para a avaliação usando
uma instância
AuthorAttribution. |
Comparação de código
Esta seção compara o código dos métodos de pesquisa de texto para ilustrar as diferenças
entre as avaliações de lugares no PlacesService legado e na classe Place mais recente.
Serviço de lugares (legado)
O snippet a seguir chama getDetails() para solicitar detalhes do lugar, incluindo avaliações, e mostra o primeiro resultado da avaliação em uma janela de informações.
const request = {
placeId: "ChIJpyiwa4Zw44kRBQSGWKv4wgA", // Faneuil Hall Marketplace, Boston, MA
fields: ["name", "formatted_address", "geometry", "reviews"],
};
const service = new google.maps.places.PlacesService(map);
service.getDetails(request, (place, status) => {
if (
status === google.maps.places.PlacesServiceStatus.OK &&
place &&
place.geometry &&
place.geometry.location
) {
// If there are any reviews display the first one.
if (place.reviews && place.reviews.length > 0) {
// Get info for the first review.
let reviewRating = place.reviews[0].rating;
let reviewText = place.reviews[0].text;
let authorName = place.reviews[0].author_name;
let authorUri = place.reviews[0].author_url;
// Format the review using HTML.
contentString =`
<div id="title"><b>${place.name}</b></div>
<div id="address">${place.formatted_address}</div>
<a href="${authorUri}" target="_blank">Author: ${authorName}</a>
<div id="rating">Rating: ${reviewRating} stars</div>
<div id="rating"><p>Review: ${reviewText}</p></div>`;
} else {
contentString = `No reviews were found for ${place.name}`;
}
const infowindow = new google.maps.InfoWindow({
content: contentString,
ariaLabel: place.displayName,
});
// Add a marker.
const marker = new google.maps.Marker({
map,
position: place.geometry.location,
});
// Show the info window.
infowindow.open({
anchor: marker,
map,
});
}
});
Classe Place (nova)
O snippet a seguir chama fetchFields()
método para solicitar detalhes do lugar, incluindo avaliações, e mostra o primeiro resultado da avaliação
em uma janela de informações.
// Use a place ID to create a new Place instance.
const place = new google.maps.places.Place({
id: "ChIJpyiwa4Zw44kRBQSGWKv4wgA", // Faneuil Hall Marketplace, Boston, MA
});
// Call fetchFields, passing 'reviews' and other needed fields.
await place.fetchFields({
fields: ["displayName", "formattedAddress", "location", "reviews"],
});
// If there are any reviews display the first one.
if (place.reviews && place.reviews.length > 0) {
// Get info for the first review.
let reviewRating = place.reviews[0].rating;
let reviewText = place.reviews[0].text;
let authorName = place.reviews[0].authorAttribution.displayName;
let authorUri = place.reviews[0].authorAttribution.uri;
// Format the review using HTML.
contentString =`
<div id="title"><b>${place.displayName}</b></div>
<div id="address">${place.formattedAddress}</div>
<a href="${authorUri}" target="_blank">Author: ${authorName}</a>
<div id="rating">Rating: ${reviewRating} stars</div>
<div id="rating"><p>Review: ${reviewText}</p></div>`;
} else {
contentString = `No reviews were found for ${place.displayName}`;
}
// Create an infowindow to display the review.
infoWindow = new google.maps.InfoWindow({
content: contentString,
ariaLabel: place.displayName,
});
// Add a marker.
const marker = new google.maps.marker.AdvancedMarkerElement({
map,
position: place.location,
title: place.displayName,
});
// Show the info window.
infoWindow.open({
anchor: marker,
map,
});