Получить JSON Place Api - PullRequest
       33

Получить JSON Place Api

0 голосов
/ 17 октября 2018

Я искал все утро, как я могу получить свои данные json из API Google, но после того, как я увидел много вопросов, я все еще не могу понять, что мне делать.Я думаю, что запутался в этом вопросе, поэтому, пожалуйста, если вы понизите голос, не могли бы вы дать мне хотя бы комментарий или что-то, что действительно может мне помочь?

Ожидаемое поведение

Я ожидаю, что получу консольный журнал или получу доступ к чему-то подобному

[
   {
      "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."
         }
      ]
   }
]

Код

это мой javascript о gmaps, автозаполнении и поиске ввода.

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

Я пытался добавить эту строку кодов, но она не работает

$.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);
});

У меня есть этот консольный журнал с ответом @markymark:

Доступ к XMLHttpRequest из источника 'null' был заблокирован политикой CORS: No 'Access-Control-Allow-Origin'заголовок присутствует на запрошенном ресурсе

Вопросы, которые мне помогают

codepen

Codepen Here

Так что я читал о CORS в этот вопрос

1 Ответ

0 голосов
/ 17 октября 2018

Это ваш URL исправлен, ваш обратный вызов по-прежнему из API javascript.Вы можете получить их с помощью простого URL.Вы можете просто вставить его в браузер и посмотреть результаты.

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

Пример для близлежащих библиотек в SF

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

Пожалуйста, не забудьте удалить ключи API.Это ваши ключи.

...