te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Getting the URL of Google Place Photo from a GoogleMapsClient response - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting the URL of Google Place Photo from a GoogleMapsClient response - Stack Overflow

programmeradmin4浏览0评论

I'm building an API endpoint which will return details and a single photo of a Google place using express.js and Node.js client library for Google Maps API Web Services. The endpoint below returns details of a place and I'm having trouble retrieving the URL of a photo. Below is the code in question.

There are two requests to the google maps client:

  1. Get place details based on req.params.id and the details contain a photos array
  2. Get photo using the photo_reference from above

    var googleMapsClient = require('@google/maps').createClient({
      key: 'mykeyhere',
      Promise: Promise
    });
    
    exports.getGglPlace = function(req, res) {
    
    googleMapsClient.place({
         placeid: req.params.id
    }).asPromise()
    .then((response) => {
      var venue = response.json.result
    
      if (venue.photos[0]) {
        googleMapsClient.placesPhoto({
          photoreference: venue.photos[0].photo_reference,
          maxwidth: 200
        }).asPromise()
        .then((photo) => {
    
          console.log("Photo:", photo); // this returns a massive chunk of data which I think contains the actual image object also
          venue.photoURL = photo.url; // this doesn't work
    
          res.send(venue);
        })
        .catch((err)=>{
          console.log("Error Getting Photo!", err);
          res.send(venue);
        })
      } else {
        res.send(venue);
      }
    })
    .catch((err) => {
      res.send(404);
    })
    }
    

Any idea how to obtain the URL from the response which is called photo in the code above?

If I try going to the API directly through the browser or Postman, the URL gets redirected to the actual source URL of the image, which is what I want to add to my venue object.

API request example: ;photoreference=CmRaAAAA8NPP1nJJ7RCzcQDGUrpBHJXlzlQkN74dcyQJ2ytVpeYIu47sR-8dfCjke1J5exP-HpkayaXOc26ShsVKkXOaJZBOdpmExUfCzUTIBN3x0uPfR5Nt3PnN-a3GoRVZ7YxKEhBvqXF356Tn9mBJ7lA_JQ_7GhQMKvZkOk-Rs9knsansx5yuhfIvsQ&sensor=false&key=mykeyhere

Redirects to (this is what I want photo.url to return):

Any help is appreciated.

P.S. My first post here - sorry if I'm not clear enough with my question.

I'm building an API endpoint which will return details and a single photo of a Google place using express.js and Node.js client library for Google Maps API Web Services. The endpoint below returns details of a place and I'm having trouble retrieving the URL of a photo. Below is the code in question.

There are two requests to the google maps client:

  1. Get place details based on req.params.id and the details contain a photos array
  2. Get photo using the photo_reference from above

    var googleMapsClient = require('@google/maps').createClient({
      key: 'mykeyhere',
      Promise: Promise
    });
    
    exports.getGglPlace = function(req, res) {
    
    googleMapsClient.place({
         placeid: req.params.id
    }).asPromise()
    .then((response) => {
      var venue = response.json.result
    
      if (venue.photos[0]) {
        googleMapsClient.placesPhoto({
          photoreference: venue.photos[0].photo_reference,
          maxwidth: 200
        }).asPromise()
        .then((photo) => {
    
          console.log("Photo:", photo); // this returns a massive chunk of data which I think contains the actual image object also
          venue.photoURL = photo.url; // this doesn't work
    
          res.send(venue);
        })
        .catch((err)=>{
          console.log("Error Getting Photo!", err);
          res.send(venue);
        })
      } else {
        res.send(venue);
      }
    })
    .catch((err) => {
      res.send(404);
    })
    }
    

Any idea how to obtain the URL from the response which is called photo in the code above?

If I try going to the API directly through the browser or Postman, the URL gets redirected to the actual source URL of the image, which is what I want to add to my venue object.

API request example: https://maps.googleapis./maps/api/place/photo?maxwidth=400&photoreference=CmRaAAAA8NPP1nJJ7RCzcQDGUrpBHJXlzlQkN74dcyQJ2ytVpeYIu47sR-8dfCjke1J5exP-HpkayaXOc26ShsVKkXOaJZBOdpmExUfCzUTIBN3x0uPfR5Nt3PnN-a3GoRVZ7YxKEhBvqXF356Tn9mBJ7lA_JQ_7GhQMKvZkOk-Rs9knsansx5yuhfIvsQ&sensor=false&key=mykeyhere

Redirects to (this is what I want photo.url to return): https://lh3.googleusercontent./p/AF1QipPVD12HA5FBnjmiqVLphYgjfPtIPydn4Ie-xGKr=s1600-w200

Any help is appreciated.

P.S. My first post here - sorry if I'm not clear enough with my question.

Share Improve this question edited Dec 6, 2017 at 14:43 boomer4you asked Nov 25, 2017 at 10:31 boomer4youboomer4you 1511 silver badge7 bronze badges 1
  • I found a similar question here, but it has no answer – boomer4you Commented Nov 25, 2017 at 18:36
Add a ment  | 

5 Answers 5

Reset to default 9

Here is how I solved it. It doesn't seem perfect, but it does the job.

The response contains a req section which has keys in there that I was able to use to build the URL. Specifically, the response.req.socket._host key and the response.req.path key.

Here is what it looks like in my code (where photo is the response from google API)

venue.photoURL = "https://" + photo.req.socket._host + photo.req.path;

photo.req.socket._host gives me lh3.googleusercontent.

photo.req.path gives me /p/AF1QipPVD12HA5FBnjmiqVLphYgjfPtIPydn4Ie-xGKr=s1600-w200

Results of the constructed URL to the photo is: https://lh3.googleusercontent./p/AF1QipPVD12HA5FBnjmiqVLphYgjfPtIPydn4Ie-xGKr=s1600-w200

This code below works on my clientside JS project. Thus, I am able to retrieve place data and its photos as useful link and push it into img src on my html. Maybe it could be useful.

   var service = new google.maps.places.PlacesService(map);
   service.nearbySearch({
        location: latlonNearby,
        radius: 500,
        type: NearbyTypes,
        keyword: ['kafe', 'caffe']
   }, callback);
   function callback(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
        for (let i = 0; i < results.length; i++) {
           // I retrieved first added photo "photos[0]" //
           var placePhotoUrl = results[i].photos[0].getUrl({maxWidth:640}); 
           console.log(placePhotoUrl);
           // Then Do Whatever You Want with this placePhotoUrl //
           }
        }
    }

you can do this

with axios

axios.get(url).then(res => {
  console.log(res.request._redirectable._options.href));
});

with node-fetch

fetch(url).then(res => {
  console.log(res.url);
});

IMPORTANT: make sure you have the package you use installed and required and make sure the url you use works in your browser.

The response of a successful Place Photo request will be an image, not an object literal.

https://developers.google./places/web-service/photos

The way the browse knows how to redirect to the photo is via a header. If you check out the response you will see it returns a 302 (redirect) and follows the response header location. You should be able to grab that header in express via:

res.get('location');
// => "image url"

If you use postman, you must turn of settings->automatically follow redirects, then you'll se something like this

   <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="https://lh3.googleusercontent./p/blahblah">here</A>.
</BODY></HTML>

Follow url to find image.

发布评论

评论列表(0)

  1. 暂无评论