user9269133
user9269133

Reputation: 141

How do I make a query to Google Places API?

I'm trying to make a client-side jquery request on an HTML page (in my Spring project) to the Google Places API so I can determine the ratings of a particular business type within a radius of x,y. At the moment I'm trying to do it like so:

  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"));
            }
           });
          });

    } 

However Michael Geary's answer to this question Google's Places API and JQuery request - Origin http://localhost is not allowed by Access-Control-Allow-Origin has lead me to believe I cannot use an Ajax jquery to access the API this way and I have to "use the Places Library from the Maps API V3. (As I) can't just hit a URL directly from JavaScript or jQuery code."

With that being said I've found the documentation to do this to be quite broad and resources online seem to be quite limited. Has anyone any experience on how to simply get the rating elements from the API stored into an array in JS so I can calculate the average and display it in a text box?

In case it's needed this how the XML formatted API looks

<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>

Upvotes: 1

Views: 1638

Answers (1)

Michael Geary
Michael Geary

Reputation: 28850

My previous advice remains the same: you can't use the server-oriented web service version of the Places API. You have to use the JavaScript client library. It is much easier to use than the web service API (even if you were allowed to use that), because you don't have to parse any XML, just access the object properties that the client library provides.

There are several examples in the Places Library documentation. The Place Search example is fairly close to what you are doing. It looks like you want to access the rating for a place, and that is easy with the JavaScript library; simply use the rating property of your place object (or whatever name you give that variable).

I took the Place Search example and updated the fiddle to illustrate accessing the rating property. Try it out and see if it helps answer your question.

In any case, the bottom line is unchanged: you can't use the web service API, you need to use the JavaScript client library, but that is a Good Thing, as the client library does most of the work for you.

If the question is how to compute the average rating for the places you receive back from the API, that is simple: write a loop and do the arithmetic. If you look at the fiddle you will see where it has a loop that iterates over the results variable that the API callback receives. The loop in the fiddle creates a marker for each element of results, but you can do whatever you want there. Just add up all the rating values and divide the total by results.length and you have your average. Of course check that the length is nonzero, so you don't divide by zero.

For example, if you have a results variable with the array of places results, you could do:

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

Upvotes: 1

Related Questions