Подтвердить что ты не робот

Как получить изображение места из карт Google или мест API

Я использую Google Places API для извлечения данных о местах, но не могу найти, как получить изображение этого места, Google Places API просто предоставляет значок, который не то же самое. Мне нужна фотография, которую вы получаете, когда вы ищете место на Картах Google в веб-браузере, например. В Panoramio обычно больше фотографий, но Panoramio API может искать только фотографии по местоположению, а не по определенному ресторану или названию отеля, например. Любые идеи?

4b9b3361

Ответ 1

API-интерфейс Places даст вам координаты (широта и долгота) в указать подробный ответ; вы можете отправить координаты в Panoramio API.

Например (рисунок из примеров в документах API):

https://maps.googleapis.com/maps/api/place/details/json?reference=<big long key for place>&sensor=true&key=AIzaSyAiFpFd85eMtfbvmVNEYuNds5TEF9FjIPI

Ответ:

{
  "html_attributions" : [],
  "result" : {
    "address_components" : [
      {
        "long_name" : "48",
        "short_name" : "48",
        "types" : [ "street_number" ]
      },
      {
        "long_name" : "Pirrama Road",
        "short_name" : "Pirrama Road",
        "types" : [ "route" ]
      },
      {
        "long_name" : "Pyrmont",
        "short_name" : "Pyrmont",
        "types" : [ "locality", "political" ]
      },
      {
        "long_name" : "NSW",
        "short_name" : "NSW",
        "types" : [ "administrative_area_level_1", "political" ]
      },
      {
        "long_name" : "AU",
        "short_name" : "AU",
        "types" : [ "country", "political" ]
      },
      {
        "long_name" : "2009",
        "short_name" : "2009",
        "types" : [ "postal_code" ]
      }
    ],
    "formatted_address" : "5/48 Pirrama Road, Pyrmont NSW, Australia",
    "formatted_phone_number" : "(02) 9374 4000",
    "geometry" : {
      "location" : {
        "lat" : -33.8669710,
        "lng" : 151.1958750
      }
    },
    "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
    "id" : "4f89212bf76dde31f092cfc14d7506555d85b5c7",
    "international_phone_number" : "+61 2 9374 4000",
    "name" : "Google Sydney",
    "rating" : 4.60,
    "reference" : "CnRlAAAAAfV6JIqSzL8Cf4VnXn0EaI1d5k3IPhdkEonq0MxiUbQFFSVuptVbXbNH4mrevb0bc7G8yWqTUv76i4KTuO_Wf3OrRHjCJJwzQ0mNLjbYGSVqy2eqyrgOUkl6S_sJfTbHzWZYrfPy7KZaet0mM5S6thIQJYuy5v_JD--ZxXEJLWTQRRoU5UaciXBBo89K-bce18Ii9RsEIws",
    "types" : [ "store", "establishment" ],
    "url" : "http://maps.google.com/maps/place?cid=10281119596374313554",
    "vicinity" : "5/48 Pirrama Road, Pyrmont",
    "website" : "http://www.google.com.au/"
  },
  "status" : "OK"
}

Мы видим, что координаты          "место нахождения": {            "лат": -33,8669710,            "lng": 151.1958750         }

Затем мы можем отправить запрос в Panoramio, вставив координаты, а также небольшую комнату для маневра с обеих сторон (я сделал +/- 0,002 градуса, квадрат 200 м x 200 м на экваторе, как правило, меньше). http://www.panoramio.com/map/get_panoramas.php?set=public&from=0&to=20&minx=-33.868&miny=151.193&maxx=-33.864&maxy=151.197&size=medium&mapfilter=true

Вам может потребоваться некоторая фильтрация ответов, чтобы получить самое близкое фото, но это должно дать вам что-то, с чем можно работать.

Ответ 3

API Places теперь поддерживает возврат одной фотографии места, если она доступна для запроса поиска места, и до десяти фотографий места для запроса сведений о месте.

Если массив фотографий возвращается по вашему запросу, вы можете передать photo_reference из содержащегося фотообъекта в Разместить запрос фото с помощью maxheight и/или maxwidth, sensor и key параметры:

https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRvAAAAwMpdHeWlXl-lH0vp7lez4znKPIWSWvgvZFISdKx45AwJVP1Qp37YOrH7sqHMJ8C-vBDC546decipPHchJhHZL94RcTUfPa1jWzo-rSHaTlbNtjh-N68RkcToUCuY9v2HNpo5mziqkir37WU8FJEqVBIQ4k938TI3e7bf8xq-uwDZcxoUbO_ZJzPxremiQurAYzCTwRhE_V0&sensor=false&key=AddYourOwnKeyHere

Подробнее см. в документации.

Ответ 4

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Places Searchbox</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 50%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #description {
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
      }

      #infowindow-content .title {
        font-weight: bold;
      }

      #infowindow-content {
        display: none;
      }

      #map #infowindow-content {
        display: inline;
      }

      .pac-card {
        margin: 10px 10px 0 0;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        background-color: #fff;
        font-family: Roboto;
      }

      #pac-container {
        padding-bottom: 12px;
        margin-right: 12px;
      }

      .pac-controls {
        display: inline-block;
        padding: 5px 11px;
      }

      .pac-controls label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 400px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      #title {
        color: #fff;
        background-color: #4d90fe;
        font-size: 25px;
        font-weight: 500;
        padding: 6px 12px;
      }
      #target {
        width: 345px;
      }
    </style>
  </head>
  <body>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map"></div>
    <div id="place-list"></div>
    <script>
      // This example adds a search box to a map, using the Google Place Autocomplete
      // feature. People can enter geographical searches. The search box will return a
      // pick list containing a mix of places and predicted search terms.

      // This example requires the Places library. Include the libraries=places
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

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

        // 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);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map 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() {
          var places = searchBox.getPlaces();

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

          // 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) {
            if (!place.geometry) {
              console.log("Returned place contains no geometry");
              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)
            };

            var photoUrl = place.photos[0].getUrl({maxWidth: 400, maxHeight: 400});
            var img = document.createElement("img");
            img.setAttribute('src', photoUrl + "photo.jpg");
            document.getElementById('place-list').appendChild(img);

            // Create a marker for each place.
            markers.push(new google.maps.Marker({
              map: map,
              icon: photos[0].getUrl({'maxWidth' : 35,maxHeight' : 35})
              title: place.name,
              position: place.geometry.location
            }));

            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });
      }

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=<KEY_API>&libraries=places&callback=initAutocomplete"
         async defer></script>
  </body>
  </html>

Ответ 5

  1. Сначала получите photo_reference из ответа:

     var photoRef;
     if (data.results[i].photos && Array.isArray(data.results[i].photos)) {
     photoRef = data.results[i].photos[0].photo_reference;
     }
    
  2. Используйте конечную точку API Google Фото, чтобы ПОЛУЧИТЬ фотографию/фотографию места:

https://maps.googleapis.com/maps/api/place/photo?maxwidth=960&photoreference="+ photoRef + "& key = AIzaSyBp0cy7ti0z5MJMAwWiPMNvbJobmWYGyv4 'alt=' '/>

  1. Убедитесь сами:

enter image description here