2011-12-11 12 views
12

Estoy usando Google Places API para recuperar datos sobre lugares, pero no pude encontrar cómo obtener una imagen de ese lugar, Google Places API solo proporciona un icono que no es el mismo. Necesito la foto que obtienes cuando buscas un lugar en Google Maps en un navegador web, por ejemplo. Por lo general, hay más imágenes de Panoramio, pero Panoramio API solo puede buscar imágenes por ubicación y no por un restaurante o nombre de hotel en particular, por ejemplo. ¿Algunas ideas?Cómo obtener una imagen de un lugar de google maps o lugares API

Respuesta

9

La API Places le dará las coordenadas (latitud y longitud) en el place detail response; a continuación, puede enviar las coordenadas al Panoramio API.

Por ejemplo (dibujo a partir de ejemplos en los documentos de la API):

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

Respuesta:

{ 
    "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" 
} 

Podemos ver que las coordenadas son "localización": { "lat": -33.8669710, "lng": 151.1958750 }

Luego podemos enviar una solicitud a Panoramio, insertando las coordenadas, más un pequeño margen de maniobra a cada lado (hice +/- 0.002 grados, una forma de 200 m x 200 m cuadrados en el ecuador, generalmente más pequeña). 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

Es posible que tenga que filtrar las respuestas para obtener la foto más cercana, pero esto debería darle algo con qué trabajar.

+0

Gracias, estaba pensando en eso, no necesariamente dará la imagen del lugar correcto, pero supongo que es lo más cercano que puede obtener. Es extraño que tengan fotos en el sitio web pero no las den de todos modos en los mapas o lugares. – user975869

+1

Panoramio ya no es una cosa. El sitio web (http://www.panoramio.com/) dice "Panoramio ya no está disponible después del 4 de noviembre de 2016". Las solicitudes de API responden con 404 No encontrado. – salomvary

4

La API Lugares ahora es compatible con el regreso de una foto de su lugar si está disponible para un Place Search request y hasta diez fotos de sitios para una Place Details request.

Si una matriz de fotos se devuelve con su solicitud, usted puede pasar el photo_reference de una foto del objeto contenida en un Place Photo request con el maxheight y/o maxwidth, sensor y key parámetros:

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

Por favor, vea la documentation para más detalles.

+0

Veo esa foto. Pero quiero usarlo en JS. ¿Puedo tenerlo en formato JSON con una URL? – user132522

0
<!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'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() { 
      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> 
+1

Si bien este fragmento de código puede resolver la pregunta, [incluyendo una explicación] (// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) realmente ayuda a mejorar la calidad de su publicación. Recuerde que usted está respondiendo la pregunta a los lectores en el futuro, y es posible que esas personas no sepan los motivos de su sugerencia de código.Por favor, intente no saturar su código con comentarios explicativos, ¡esto reduce la legibilidad tanto del código como de las explicaciones! – kayess

Cuestiones relacionadas