Las opiniones de lugares te permiten agregar opiniones y calificaciones de los usuarios a tus páginas web. En esta página,
se explican las diferencias entre las opiniones de lugares que se usan en la clase Place(nueva) y PlacesService (heredada), y se proporcionan algunos fragmentos de código para la
comparación.
PlacesService(heredada) muestra un array dePlaceReviewinstancias como parte del objetoPlaceResultpara cualquier solicitud degetDetails()si el camporeviewsse especifica en la solicitud.Place(nueva) muestra un array de instancias deReviewcomo parte de una solicitud defetchFields()si el camporeviewsse especifica en la solicitud.
En la siguiente tabla, se enumeran algunas de las principales diferencias en el uso de las opiniones de lugares entre la clase Place y PlacesService:
PlacesService (heredada) |
Place (nueva) |
|---|---|
PlaceReview interfaz |
Review clase |
Los métodos requieren el uso de una devolución de llamada para controlar el objeto de resultados y
google.maps.places.PlacesServiceStatus respuesta. |
Usa Promises y funciona de forma asíncrona. |
Los métodos requieren una verificación de PlacesServiceStatus. |
No se requiere una verificación de estado, se puede usar el manejo de errores estándar. Obtén más información. |
PlacesService debe crearse una instancia con un mapa o un
elemento div. |
Place se puede crear una instancia de donde sea necesario, sin una
referencia a un mapa o un elemento de página. |
PlaceReview muestra datos de atribución para la opinión con los campos author_name, author_url y profile_photo_url. |
Review muestra datos de atribución para la opinión con
una instancia de
AuthorAttribution. |
Comparación de código
En esta sección, se compara el código de los métodos de búsqueda de texto para ilustrar las diferencias
entre las opiniones de lugares en el heredado PlacesService y la clase Place más reciente.
Servicio de Places (heredado)
En el siguiente fragmento, se llama a getDetails() para solicitar detalles del lugar, incluidas las opiniones, y se muestra el primer resultado de la opinión en una ventana de información.
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,
});
}
});
Clase Place (nueva)
En el siguiente fragmento, se llama al fetchFields()
método para solicitar detalles del lugar, incluidas las opiniones, y se muestra el primer resultado de la opinión
en una ventana de información.
// 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,
});