Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我如何从Google Places获取一组地点的坐标,然后在完成所有操作后使用结果?_Javascript_Node.js_Promise_Google Places Api_Google Places - Fatal编程技术网

Javascript 我如何从Google Places获取一组地点的坐标,然后在完成所有操作后使用结果?

Javascript 我如何从Google Places获取一组地点的坐标,然后在完成所有操作后使用结果?,javascript,node.js,promise,google-places-api,google-places,Javascript,Node.js,Promise,Google Places Api,Google Places,我有一系列地名,例如: const places = ['King Square, London', 'Empire State Building', 'Great Wall of China']; const places = [ { name: 'King Square, London', position: { latitude: ..., longitude: ... } }, ... ]; 我需要一个新的对象数组,为地名数组中的每个元素设置位置,例如: const plac

我有一系列地名,例如:

const places = ['King Square, London', 'Empire State Building', 'Great Wall of China'];
const places = [
  { name: 'King Square, London', position: { latitude: ..., longitude: ... } },
  ...
];
我需要一个新的对象数组,为地名数组中的每个元素设置位置,例如:

const places = ['King Square, London', 'Empire State Building', 'Great Wall of China'];
const places = [
  { name: 'King Square, London', position: { latitude: ..., longitude: ... } },
  ...
];
我想我必须这样做:

const places = [];

['King Square, London', 'Empire State Building', 'Great Wall of China'].forEach(placeName => {
  axios
  .get(`https://maps.googleapis.com/maps/api/place/textsearch/json?key=GOOGLE_PLACES_API_KEY&query=${placeName}`)
  .then(response => {
    if (!!response && !!response.results && !!response.results[0]) {
      const searchResult = response.results[0];

      if (!!searchResult) {
        axios
          .get(`https://maps.googleapis.com/maps/api/place/details/json?key=GOOGLE_PLACES_API_KEY&placeid=${searchResult.place_id}`)
          .then(response => {
            const placeResult = response.result;

            if (!!placeResult) {
              places.push({ name: placeName, position: placeResult.geometry.location })
但它似乎不起作用

它应该是什么样子,以便我可以填充
位置
,并在填充后使用数组?在使用它之前,我是否必须使用承诺来确保它已填充?

使用

更新现有代码的步骤:

  • 使用而不是将承诺存储在数组中
  • 让回调函数返回承诺(即来自
    axios.get().then()的返回值)
  • 调用的响应将具有包含结果的数据属性,因此请使用
    response.data.results
    而不是
    response.results
  • 再次兑现诺言
  • 然后,在设置promises数组后,可以使用Promise.all()

    const places = [];
    //1 - store promises in an array
    var promises = ['King Square, London', 'Empire State Building', 'Great Wall of China'].map(placeName => {
      return axios //2 - return promise
      .get(`https://maps.googleapis.com/maps/api/place/textsearch/json?key=GOOGLE_PLACES_API_KEY&query=${placeName}`)
      .then(response => {
        //3 - use response.data.results instead of response.results
        if (!!response && !!response.data && !!response.data.results && !!response.data.results[0]) {
          const searchResult = response.data.results[0];
    
          if (!!searchResult) {
            return axios //4 return nested promise
              .get(`https://maps.googleapis.com/maps/api/place/details/json?key=GOOGLE_PLACES_API_KEY&placeid=${searchResult.place_id}`)
              .then(response => {
                const placeResult = response.data.result;
    
                if (!!placeResult) {
                  places.push({ name: placeName, position: placeResult.geometry.location });
                }
              })
          }
        }
      });
    });
    //5 - After promises are done, use the places array
    Promise.all(promises).then(results => {
        console.log('places:', places);
    })
    
  • 输出:

    客户端Javascript中的示例 下面是(客户端)JavaScript的端口。注意它是如何非常相似,但是使用了StackOverflow API(因为这样就不会有CORS问题)

    var秩=[];
    var promises=[94,95].map(badgeId=>{
    返回axios.get(`https://api.stackexchange.com/2.2/badges/${badgeId}?site=stackoverflow&order=desc&sort=rank&filter=default`)
    。然后(响应=>{
    var responsebadgeId=response.data.items[0]。徽章id;
    返回axios.get(`https://api.stackexchange.com/2.2/badges/${responsebadgeId}/recipients?site=stackoverflow`)
    。然后(响应=>{
    console.log('将列组从数据中推入数组:',response.data.items[0].rank);
    ranks.push(response.data.items[0].rank);
    });
    });
    });
    承诺。所有(承诺)。然后(回复=>{
    log('承诺所有回调-列组:',列组);
    });
    
    谢谢,但我还是不知道怎么做。应该是
    var promises=names.map(name=>axios.get(URL1+?关键字='+name)。然后(response=>axios.get(URL2+)?query='+response.data.results[0]。place_id)
    ?但是我如何检索
    result.geometry.location
    ?您仍然可以进行第二次查询-请参阅上面更新的代码