-2

i searched all the morning how can I retrieve my json data from a google api, but after I saw a lot of questions I still cannot figure out what i've to do. I think I'm confused about this point, so please if you will downvote could you kindly give me at least a comment or something that can really help me ?

Expected behaviour

i expect to console log or to access something like this

[
   {
      "restaurantName":"Bronco",
      "address":"39 Rue des Petites Écuries, 75010 Paris",
      "lat":48.8737815,
      "long":2.3501649,
      "ratings":[
         {
            "stars":4,
            "comment":"Great! But not many veggie options."
         },
         {
            "stars":5,
            "comment":"My favorite restaurant!"
         }
      ]
   },
   {
      "restaurantName":"Babalou",
      "address":"4 Rue Lamarck, 75018 Paris",
      "lat":48.8865035,
      "long":2.3442197,
      "ratings":[
         {
            "stars":5,
            "comment":"Tiny pizzeria next to Sacre Coeur!"
         },
         {
            "stars":3,
            "comment":"Meh, it was fine."
         }
      ]
   }
]

Code

this is my javascript about the gmaps, autocomplete and the input search.

function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -33.8688, lng: 151.2195},
          zoom: 13,
          mapTypeId: 'roadmap'
        });

        initialize();

        google.maps.event.addListener(map, 'rightclick', function(event) {
        placeMarker(event.latLng);
            console.log(event.latLng);
        });

        function placeMarker(location) {
            var marker = new google.maps.Marker({
                position: location, 
                map: map
            });
        }

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function() {
          searchBox.setBounds(map.getBounds());
        });

        var markers = [];

        // Listen for the event fired when the user selects a prediction and retrieve    
        // more details for that place.
        searchBox.addListener('places_changed', function() {

            //check if the first sectin is already Up
            if(!sectionShow){
                $(".columnsContainer").fadeIn();
                sectionShow=true;
            }

            //automatic movements of the scroll
            document.querySelector('#map').scrollIntoView({ 
                behavior: 'smooth'         
            });

          var places = searchBox.getPlaces();  
          if (places.length == 0) {
            return;
          }

            review = [];
            //this jquery line delete the previous card if you start another research 
            $(".card-grid").parent().find('.card-wrap').remove();
          // Clear out the old markers.
          markers.forEach(function(marker) {
            marker.setMap(null);
          });
          markers = [];


          // For each place, get the icon, name and location.
          var bounds = new google.maps.LatLngBounds();
          places.forEach(function(place) {
            //hai aggiunto bounds, ricorda che stai cercando di passare le coordinate posto per posto.

            if (!place.geometry) {
              console.log("Returned place contains no geometry");
              return;
            }

              containerPlace=places;

            var photos = place.photos;
            if (!photos) {
            return;
            }

            var icon = {
              url: place.icon,
              size: new google.maps.Size(71, 71),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(17, 34),
              scaledSize: new google.maps.Size(25, 25)
            };

              // remember to make an object instead of these variables
              var photo = photos[0].getUrl({'maxWidth': 800, 'maxHeight': 900})
              var title = place.name;
              var rating = place.rating;
              var address = place.formatted_address;
              var idPlace = place.place_id;   

              console.log(idPlace);

              printCard(photo, title, rating, address, idPlace);
              initMap(idPlace, map);            

            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });
     infoWindow = new google.maps.InfoWindow;

        // GeoLocation from Here
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            $(".columnsContainer").fadeIn();
            document.querySelector('#map').scrollIntoView({ 
                behavior: 'smooth'         
            });

            infoWindow.setPosition(pos);
            infoWindow.setContent('You are here');
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }

}

My Try

I tried to add this lines of codes, but it doesn't work

$.getJSON("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=36.950030,14.537220&radius=500&type=restaurant&key=AIzaSyDWb4mliJPGjwsAhNvdDEveAd0dTe9KXxE&callback=?", function(data){
  console.log("Data: " + data);
});

I have this console log with the answer of @markymark :

Access to XMLHttpRequest at from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

Questions that helps me

codepen

Codepen Here

So i read about the CORS in this question

ADyson
  • 57,178
  • 14
  • 51
  • 63
Legeo
  • 784
  • 4
  • 20
  • 44
  • 1
    "doesn't work" isn't an error or problem statement. Your question is great right up to that point, but you also need to explain precisely what behaviour you're seeing instead of what you expected. Check your browser's console and network tabs for errors, if you haven't already. Step through your code with the debugger and check the variable values and the path your code is taking, to see what is actually occurring. – ADyson Oct 17 '18 at 09:31
  • Yeah, i will correct quickly, i get this error on the console "Access to XMLHttpRequest at from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource" . – Legeo Oct 17 '18 at 09:33
  • 1
    Ok thanks. Please read https://stackoverflow.com/questions/12052483/origin-null-is-not-allowed-by-access-control-allow-origin . That error is because you need to execute your page in a proper webserver (i.e. over `http://` or `https://`, not the `file://` protocol). – ADyson Oct 17 '18 at 10:02
  • 1
    You can easily install a webserver on your machine using Apache or IIS (depending on your operating system), there are other products too, possibly even simpler to set up, if you search online. – ADyson Oct 17 '18 at 10:07
  • Thanks for all of your answer, so it's correct to say that if upload on http or https and i use the `$.getJSON("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=36.950030,14.537220&radius=500&type=restaurant&key=AIzaSyDWb4mliJPGjwsAhNvdDEveAd0dTe9KXxE&callback=?", function(data){ console.log("Data: " + data); }); `it will console log all the json data, right ? – Legeo Oct 17 '18 at 10:08
  • It sounds like it should, unless there is another bug we haven't encountered yet. You can try it very easily in your own codepen. – ADyson Oct 17 '18 at 10:08
  • Thanks a lot! i can close the question now :) really thanks! – Legeo Oct 17 '18 at 10:08

1 Answers1

1

This is your URL fixed, you had your callback still from the javascript API. You can fetch those with a simple URL. You can just paste it in the browser and see the results.

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=36.950030,14.537220&radius=500&type=restaurant&key=AIzaSyDWb4mliJPGjwsAhNvdDEveAd0dTe9KXxE

An example for nearby Libraries in SF

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.7749,-122.4194&radius=1000&type=library&key=AIzaSyDWb4mliJPGjwsAhNvdDEveAd0dTe9KXxE

Please remember to delete your API keys. These are your keys.

markymark
  • 145
  • 4
  • if I use this code in the .getJson it gives me the error Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.7749,-122.4194&radius=1000&type=library&key=MyApiKey' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. – Legeo Oct 17 '18 at 09:43
  • Could you use the JavaScript places API instead of passing URLS? In order to avoid CORS issues. Here is an example from the docs, https://developers.google.com/maps/documentation/javascript/places Let me know if you need more help – markymark Oct 17 '18 at 10:10