如何查询 Google 个地点 API?

How do I make a query to Google Places API?

我正在尝试在 HTML 页面(在我的 Spring 项目中)向 Google 地点发出客户端 jquery 请求 API 这样我就可以确定 x,y 半径内特定业务类型的评级。目前我正在尝试这样做:

  function getCafe(){

       $(document).ready(function(){
           $('.search_latitude').val(marker.getPosition().lat());
           $('.search_longitude').val(marker.getPosition().lng());

           // These are lat long values calculated by the user's searched location on a google map on the client side
           var Lat = marker.getPosition().lat();
           console.log(Lat);
           var Long = marker.getPosition().lng();
           console.log(Long);
           var cafeRatings = [];
           // Ive disclosed my API Key
           var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=" + Lat + "," + Long + "&radius=500&type=restaurant&keyword=cruise&key=MY_API_KEY";

           $.ajax({
            type: "GET",
            dataType: "xml",
            url: url,
            success: function(xml) {
                $(xml).find('results').each(function(){
                    $(this).find("rating").each(function(){
                        var rating = $(this).text();
                        cafeRatings.push(rating);
                    });
                });
               //This is a simple debug to display the contents of the rating array to ensure the parse worked correctly
                alert(cafeRatings.join("\n"));
            }
           });
          });

    } 

但是 Michael Geary 对这个问题的回答 让我相信我不能使用 Ajax jquery 以这种方式访问​​ API,我必须"use the Places Library from the Maps API V3. (As I) can't just hit a URL directly from JavaScript or jQuery code."

话虽如此,我发现执行此操作的文档非常广泛,在线资源似乎非常有限。有没有人知道如何简单地将 API 中的评分元素存储到 JS 中的数组中,以便我可以计算平均值并将其显示在文本框中?

以防需要 XML 格式 API 的外观

<PlaceSearchResponse>
<status>OK</status>


 <result>
         <name>Sydney Showboats</name>
         <vicinity>32 The Promenade, Sydney</vicinity>
         <type>travel_agency</type>
         <type>restaurant</type>
         <type>food</type>
         <type>point_of_interest</type>
         <type>establishment</type>
    <geometry>
        <location>
        <lat>-33.8675570</lat>
        <lng>151.2015270</lng>
        </location>
          <viewport>
           <southwest>
             <lat>-33.8689120</lat>
             <lng>151.2001126</lng>
           </southwest>
           <northeast>
             <lat>-33.8662141</lat>
             <lng>151.2028105</lng>
           </northeast>
          </viewport>
    </geometry>
    <rating>3.8</rating> <------ This is the element im trying to ad to the array
    <icon>
    https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png
    </icon>
    <reference>
    CmRSAAAALItuCtuLapozzsjq3dmKqj7NDik149XsgUwHD3ob5AWfHYlZtykuJbQa0cq0GMqX8dRgucTCmitnXgV-ekE3GfV7910rzHhx3ZuadVYNuWMzLDVZDCj2G1yiBw8r_hhgEhCPDXsniaZ2ZrkvYyXFfmQrGhSzdmkAEz4stXNx2qFe-GqAlldzgw
    </reference>
    <id>ce4ffe228ab7ad49bb050defe68b3d28cc879c4a</id>
    <opening_hours>
    <open_now>false</open_now>
    </opening_hours>
    <photo>
    <photo_reference>
    CmRaAAAAh4dP9hsZ_6515QNxouVnuYFYKemmf8BE01rcaOvkFlILQiwGNe_OAX0ikmobMmWZJvyjsFEsn7j1TFhauHSrek8nY5GsW24_6nwJsqEwHTUC10SL5gQITHhkdam50G1PEhCP-C7Of2mkjqJCTYFeYGWuGhQjVoWASHiGSp3WHm26Bh2sYOglZw
    </photo_reference>
    <width>2048</width>
    <height>1152</height>
    <html_attribution>
    <a href="https://maps.google.com/maps/contrib/107415973755376511005/photos">Sydney Showboats</a>
    </html_attribution>
    </photo>
    <place_id>ChIJjRuIiTiuEmsRCHhYnrWiSok</place_id>
    <scope>GOOGLE</scope>
    </result>
........
</PlaceSearchResponse>

我之前的建议保持不变:您不能使用 Places 的面向服务器的 Web 服务版本 API。您必须使用 JavaScript 客户端库。它比 Web 服务 API(即使您被允许使用它)更容易使用,因为您不必解析任何 XML,只需访问客户端库的对象属性提供。

Places Library documentation. The Place Search 中有几个示例与您所做的非常接近。看起来您想访问某个地方的 rating,使用 JavaScript 库可以轻松实现;只需使用 place 对象的 rating 属性(或您为该变量指定的任何名称)。

我以地点搜索为例 updated the fiddle to illustrate accessing the rating property。尝试一下,看看它是否有助于回答您的问题。

无论如何,底线是不变的:您不能使用 Web 服务 API,您需要使用 JavaScript 客户端库,但这是一件好事,因为客户端库为您完成大部分工作。

如果问题是如何计算您从 API 返回的地点的平均评分,那很简单:编写一个循环并进行算术运算。如果您查看 fiddle,您会看到它有一个循环迭代 API 回调接收的 results 变量。 fiddle 中的循环为 results 的每个元素创建一个标记,但您可以在那里做任何您想做的事情。只需将所有 rating 值相加,然后将总数除以 results.length 即可得到平均值。当然要检查长度是否为非零,这样你就不会被零除。

例如,如果您有一个包含位置结果数组的 results 变量,您可以这样做:

var totalRating = 0;
results.forEach( function( place ) {
    totalRating += place.rating;
});
var averageRating = results.length == 0 ? 0 : totalRating / results.length;