【问题标题】:How to get city photo with google places api如何使用 google places api 获取城市照片
【发布时间】:2021-01-13 12:09:44
【问题描述】:

对于我的反应天气应用程序,我需要将代表城市的每个 Card 元素附加到该城市的 img。 除了下载很多图片,我发现谷歌地方可以给我这些信息。 我从 Google Cloud Platform 注册并获得了一个 api 密钥。

这是我的卡片组件:

附言- 在googleapi url之前来自herokuapp的https是我发现处理CORS错误的唯一解决方案

import React, { useState, useEffect } from 'react'
import Card from 'react-bootstrap/Card';
import Button from 'react-bootstrap/Button';

export default function CardUI({ apiKey, place }) {
    
    const [photoUrl, setPhotoUrl] = useState('');
    
    useEffect( () => {
        fetch(`https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/details/
json?place_id=${place}&fields=photo&key=${apiKey}`)
            .then(response =>response.json())
            .then(data => {
                setPhotoUrl(data);
                console.log(data);
            })
    }, [])
    
    return (
        <Card style={{ width: '18rem' }}>
            <Card.Img variant="top" src={photoUrl} />
            <Card.Body>
                <Card.Title>Card Title</Card.Title>
                <Card.Text>
                    Some quick example text to build on the card title and make up the bulk of
                    the card's content.
                </Card.Text>
                <Button variant="primary">Go somewhere</Button>
            </Card.Body>
        </Card>
    )
}

【问题讨论】:

    标签: reactjs google-maps-api-3 react-hooks fetch google-places-api


    【解决方案1】:

    不需要任何特殊的东西或库。只需将ImagesAPI放在src标签中即可,所有图片都可以轻松加载。

     const ref = props.item.photos[0].photo_reference;
     setimg(`https://maps.googleapis.com/maps/api/place/photo?maxwidth=400
             &photoreference=${ref}&key=${APIKEY}`
           );
    
    

    在SRC标签中访问图片

     <img src={img} alt="" />
    

    或者以简单的方式

     <img 
          src="https://maps.googleapis.com/maps/api/place/photo?maxwidth=400
               &photoreference=reference&key=APIKEY"
          alt=""
      />
    
    

    【讨论】:

    • 这是最优雅的单行方式,而且很有效
    • @Parshuram Reddy 您提供的 URL 中有一个小错字。必须有一个“?”在“照片”和“最大宽度”之间。
    • 是的,我同意。谢谢@TanmayVij。
    【解决方案2】:

    您的 CORS 错误可能是因为您使用的是地方照片网络服务请求。您可以将Places Library of Maps JavaScript API 用于客户端服务。

    这是一个示例,我使用自动完成功能在您想查看的地点向您提供建议,然后在您选择地址后,它将获取地点详细信息,并且您可以获得该地点的 URL。这是sample code,下面是代码sn-p:

    /* global google */
    import React, { useEffect, useState } from "react";
    import Card from "react-bootstrap/Card";
    import Button from "react-bootstrap/Button";
    
    const CardUI = () => {
      const [photoUrl, setPhotoUrl] = useState("");
    
      useEffect(() => {
        createScriptLoadMap();
      }, []);
    
      const initialize = () => {
        let placeSearch;
        let autocomplete;
        //use Places Autocomplete
        autocomplete = new google.maps.places.Autocomplete(
          document.getElementById("autocomplete"),
          { types: ["geocode"] }
        );
        // When the user selects an address from the drop-down, populate the
        // address fields in the form.
        autocomplete.addListener("place_changed", function () {
          placeSearch = autocomplete.getPlace();
          //set photoURL from Places photos result
          setPhotoUrl(
            placeSearch.photos[0].getUrl({ maxWidth: 350, maxHeight: 350 })
          );
        });
      };
    
      const createScriptLoadMap = () => {
        var gScript = document.querySelector("[data-setted]");
        var isSetted = gScript && gScript.getAttribute("data-setted");
    
        if (!isSetted) {
          var index = document.getElementsByTagName("script")[0];
          var script = document.createElement("script");
          script.src =
            "https://maps.google.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initialize";
          script.async = true;
          script.defer = true;
          script.setAttribute("data-setted", true);
          index.parentNode.insertBefore(script, index);
          window.initialize = initialize;
        } else {
          initialize();
        }
      };
    
      return (
        <main>
          <div id="locationField">
            <input id="autocomplete" placeholder="Enter your address" type="text" />
          </div>
          <Card style={{ width: "18rem" }}>
            <Card.Img variant="top" src={photoUrl} />
            <Card.Body>
              <Card.Title>Card Title</Card.Title>
              <Card.Text>
                Some quick example text to build on the card title and make up the
                bulk of the card's content.
              </Card.Text>
              <Button variant="primary">Go somewhere</Button>
            </Card.Body>
          </Card>
        </main>
      );
    };
    
    export default CardUI;
    

    【讨论】:

    • 谢谢!...当我在谷歌上搜索我的问题的解决方案时,我看到的只是这个自动完成的 google 地方...这是获取 url 照片的唯一方法吗?隐含输入标签和搜索?知道前面的地方没有解决办法吗?
    • 如果您有已知的 placeID,可以使用Place Details Request。这是sample code
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    相关资源
    最近更新 更多