장소 리뷰를 사용하면 장소 데이터베이스의 수백만 개의 고품질 리뷰와 평점에 액세스하여 웹페이지에 표시할 수 있습니다.
샘플 소스 코드 전체 보기
이 예에서는 첫 번째 장소 리뷰를 비롯한 장소 세부정보를 검색하고 정보를 정보 창에 표시합니다.
TypeScript
let map: google.maps.Map; let centerCoordinates = { lat: 42.349134, lng: -71.083184 }; // Boston, MA let infoWindow; let contentString; async function initMap() { const { Map, InfoWindow } = await google.maps.importLibrary('maps') as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary('marker') as google.maps.MarkerLibrary; const { Place, Review } = await google.maps.importLibrary('places') as google.maps.PlacesLibrary; map = new Map(document.getElementById('map') as HTMLElement, { center: centerCoordinates, zoom: 14, // ... }); // Use a place ID to create a new Place instance. const place = new 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;< // F><o>rmat the review usin<g ><HTML>. con<tentString =` > div id="ti<tle&>quot;b${place<.displayName}/b/div div i>d="address"<${>place.formatt<edAddress}/div > a href="${au<thor>Uri}" ta<rget="_bla><n>k"Author: ${auth<or><Name>}/a div id="rating"Rating: ${reviewRating} stars/div div id="rating"pReview: ${reviewText}/p/div`; } else { contentString = 'No reviews were found for ' + place.displayName + '.'; } // Create an infowindow to display the review. infoWindow = new InfoWindow({ content: contentString, ariaLabel: place.displayName, }); // Add a marker. const marker = new AdvancedMarkerElement({ map, position: place.locati title: place.displayName, }); // Show the info window. infoWindow.open({ anchor: marker, map, }); } initMap();index.ts
JavaScript
let map; let centerCoordinates = { lat: 42.349134, lng: -71.083184 }; // Boston, MA let infoWindow; let contentString; async function initMap() { const { Map, InfoWindow } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); const { Place, Review } = await google.maps.importLibrary("places"); map = new Map(document.getElementById("map"), { center: centerCoordinates, zoom: 14, // ... }); // Use a place ID to create a new Place instance. const place = new Place({ id: "ChIJpyiwa4Zw44kRBQSGWKv4wgA", // Faneuil Hall Marketplace, Boston, MA }); // Call fetchFields, passing 'reviews' and other needed fields. await place.fetchFields({ fields: ["displayName", "formattedAddress", "location", &qu&&ot;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].authorAttri><b>ution.uri; // F<or><mat >the review us<ing HTML. co>ntentString = ` < d>iv id="t<itle"b${place.displayName}/b/div> div id=&<qu>ot;address&qu<ot;${place.form>attedAddress}/div < a h>ref="${a<uthorUri}">< >target="_blank&q<uo><t;Au>thor: ${authorName}/a div id="rating"Rating: ${reviewRating} stars/div div id="rating"pReview: ${reviewText}/p/div`; } else { contentString = "No reviews were found for " + place.displayName + "."; } // Create an infowindow to display the review. infoWindow = new InfoWindow({ content: contentString, ariaLabel: place.displayName, }); // Add a marker. const marker = new AdvancedMarkerEle map, position: place.location, title: place.displayName, }); // Show the info window. infoWindow.open({ anchor: marker, map, }); } initMap();index.js
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html> <head> <title>Place Reviews</title> <link rel="stylesheet" type="text/css" >href=<"./style.css" / script ><type=&q>uot<;modu>le&<quot>; src<="./ind><ex.j>s"<;/script /head bod>y < div i>d=&>quot;map"/div !-- prettier-ignore -- script(g={var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m>=document,b=window;b=b[c]||(b>[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=h||(h=new Promise(async(f,n)={awa>it (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=h=n(Error(p+>" c&&ould not loa>d."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.hea<d.appen>d(a<)}));>d<[l]?c>n(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=r.add(f)u().then(()=d[l](f,...n))}) ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});/script /body /htmlindex.html
샘플 사용해 보기
장소 리뷰 가져오기
장소의 리뷰 데이터를 가져오려면 fetchFields()
요청 매개변수에 reviews
필드를 포함합니다. 결과 장소 인스턴스에는 필요한 리뷰 정보에 액세스할 수 있는 Review
객체 배열이 포함됩니다.
다음 예는 리뷰에 대한 장소 세부정보 요청을 실행하는 것을 보여줍니다.
// Use a place ID to create a new Place instance. const place = new 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 displ>ay 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; // Fo<rmat the revie><w> using HTML. conte<nt><Stri>ng = ` < div id=&qu>ot;title"b${place.di<spla>yName}/b/di<v div id="address">;${place.formattedAdd<re>ss}/div < a href=&>quot;${authorUri}" targe<t=&q>uot;_blank&<quot;Author: ${><a>uthorName}/a < ><div >id="rating"Rating: ${reviewRating} stars/div div id="rating"pReview: ${reviewText}/p/div`; } else { contentString = "No reviews were found for " + place.displayName + "."; } / an infowindow to display the review. infoWindow = new InfoWindow({ content: contentString, ariaLabel: place.displayName, }); index.js
Review
인스턴스에는 다음이 포함됩니다.
AuthorAttribution
- 사용자가 제공한
rating
입니다. publishTime
(날짜) 및relativePublishTimeDescription
(현재 시간과 관련된 검토 시간(예: '한 달 전'))- 리뷰
text
- 리뷰가 작성된 언어를 나타내는
textLanguageCode
입니다.
장소의 전체 평점을 가져오려면 Place.rating
속성을 사용하세요 (fetchFields()
요청 매개변수에서 rating
필드를 요청해야 함).
작성자 저작자 표시
리뷰를 표시할 때는 리뷰의 작성자 저작자 표시도 표시해야 합니다. AuthorAttribution
클래스를 사용하여 기여 분석을 반환합니다. 저작자 표시는 저자 이름(displayName
), Google 지도 프로필의 URI (uri
), 저자 사진의 URI (photoURI
)로 구성됩니다. 다음 스니펫은 저작자 표시의 displayName
, uri
, photoURI
를 반환하는 것을 보여줍니다.
let authorName = place.reviews[0].authorAttribution!.displayName; let authorUri = place.reviews[0].authorAttribution!.uri; let authorPhoto = place.reviews[0].authorAttribution!.photoURI;