Getting JSON file from Google Places API

2019-07-21 16:49发布

I am trying to use the Places API and I was initially trying to use $.ajax from jQuery but I kept getting an unexpected token error on the first element of the file. But I realized then that you can't get JSONP from the Places API. So below is a sample of what it returns, I can't for the life of me get it to print id into console (for starters)...Could someone maybe point me in the right direction?

JSON returned from Places:

{
   "html_attributions" : [],
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : 33.7862590,
               "lng" : -117.8531270
            }
         },
         "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
         "id" : "5be9a13a28635cf8fd2ef3c62c24d51277a4ba58",
         "name" : "Kimmies Coffee Cup",
         "rating" : 3.30,
         "reference" : "CnRpAAAANKLoOHJ1STFaFavIPjm2bpMDneGTv0AXfixyl-koF7KSK-lQSldk3c01RFJu9Gf62zXnRScte-dkPCBU8KuxCo7AMctfuaIhNkPE8RKENF9HeMlkuEg-Scp97--1VWJvjpNQjc6xRvdXsbf7V8NrSRIQnXjZBKbrSeSg2sTwBosKghoUEFlNDIN5cnVbn5n7aNtwycord-E",
         "types" : [ "restaurant", "food", "establishment" ],
         "vicinity" : "190 S Glassell St # B, Orange"
      }
      ]
}

And this is what I was trying but obviously I can't use it anymore...

 $(document).ready(function () {
    $.ajax({
      url: 'https://maps.googleapis.com/maps/api/place/search/json',
      dataType: 'jsonp',
      type: 'GET',
      data: {
        location: '33.787794,-117.853111',
        radius: 100,
        name: 'coffee',
        key: 'KEY_HERE',
        sensor: false,
      },
      success: function(data) {
        console.log(data.results[0].id);
    }
  });
});

Any suggestions would be great, thanks!

3条回答
干净又极端
2楼-- · 2019-07-21 17:28

jQuery has a parseJSON method which will create a javascript object from JSON.

Once you have this object then

obj.results will return you the results array.

results[0].id will give you the id of the first result.

查看更多
小情绪 Triste *
3楼-- · 2019-07-21 17:34

You don't need a for loop just to print the id. You can remove it and then try. Also, not sure what's 'myResult'. It doesn't appear to be defined anywhere.

查看更多
爷、活的狠高调
4楼-- · 2019-07-21 17:46

What is the result when you use datatype json instead of jsonp?

查看更多
登录 后发表回答