Как получить отзывы с Google Places API, используя поиск по соседству? - PullRequest
0 голосов
/ 27 июня 2019

Последний вопрос о моем проекте приложения для ресторана.

Я внедрил Google Places и получил рестораны в магазине моего приложения Vue, которые также отображаются на карте.

Я читал о полученииобзоры с Google Places, но не удается его реализовать.

Вот что я начал.Если кто-то может сказать мне, правильно ли я поступаю.

Код restaurantFactory.js, файл js, используемый в Магазине и управляющий всей логикой для получения ресторанов, некоторые из файла Json, другиеиз Google Places:

export default {
  getRestaurantList
};

const axios = require('axios');

// Appel Axios à la liste restaurantList.json, et de GooglePlaces, réutilisée dans le Store.
async function getRestaurantList(service, location) {
  try {
    const jsonPromise = axios.get('http://localhost:8080/restaurantList.json')
    const placesPromise = getPlacesPromise(service, location)

    const [ jsonResult, placesResult ] = await Promise.all([ jsonPromise, placesPromise ])

    const jsonRestaurantList = jsonResult.data
    const placesRestaurantList = placesResult.result.map(formatPlacesIntoJson)

    return [
      ...jsonRestaurantList,
      ...placesRestaurantList
    ]
  } catch (err) {
    console.log(err)
    return false
  }
}

/* Deux fonctions helpers de getRestaurantList utilisée dans le Store */

// Pour obtenir les places en utilisant l'API
function getPlacesPromise (service, location) {
  return new Promise((resolve) => {
    return service.nearbySearch({
      location,
      radius: 2000,
      type: ['restaurant']
    }, function (result, status) {
      // Appel de getPlacesDetails
      return resolve({ result, status })
    });
  })
}

// function getPlacesDetails (service) {
//   return new Promise((resolve) => {
//     const request = {
//     // forEach de type restaurant par place_id
//     // fields ['reviews']
//     }
//     return service.getDetails()
//   })
// }

// Pour formater les données de GooglePlaces de la même manière que les restaurants de la liste JSON
function formatPlacesIntoJson (restaurant) {
  // console.log(restaurant);
  return {
    ...restaurant,
    restaurantName: restaurant.name,
    address: restaurant.vicinity,
    lat: restaurant.geometry.location.lat(),
    long: restaurant.geometry.location.lng(),
    description: '',
    // ratings: [{
    //   stars: reviews.rating,
    //   author: reviews.author_name,
    //   comment: reviews.text
    // }]
  }
}

Store.js:

import Vue from 'vue';
import Vuex from 'vuex';

import restaurantFactory from '../interfaces/restaurantFactory';

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    restaurantList: [],
    visibleRestaurant: [],
    sortValue: [],
    boundsValue: {}
  },
  getters: {
    // Obtenir l'ID des restaurants
    getRestaurantById: (state) => {
      return (id) => {
        const restaurantIndex = getRestaurantIndex(state.restaurantList, id);
        // console.log({
        //   id,
        //   restaurantIndex
        // });
        return state.restaurantList[restaurantIndex];
      };
    },
    getRestaurantList: state => {
      return state.visibleRestaurant;
    },
    getSortValue: (state) => {
      return state.sortValue;
    },
    getBoundsValue: (state) => {
      return state.boundsValue;
    },
  },
  mutations: {
    setRestaurantList: (state, {
      list
    }) => {
      state.restaurantList = list;
    },
    // Définit les restaurants à afficher en fonction des limites de la carte et du tri par moyenne
    selectVisibleRestaurant(state) {
      const bounds = state.boundsValue;
      const range = state.sortValue;
      state.visibleRestaurant = state.restaurantList.filter((restaurant) => {
        let shouldBeVisible = true;
        let isInMap = true;
        let isInRange = true;
        // Limites cartes
        if (bounds) {
          isInMap = restaurant.long >= bounds.ga.j && restaurant.long <= bounds.ga.l && restaurant.lat >= bounds.na.j && restaurant.lat <= bounds.na.l;
          shouldBeVisible = shouldBeVisible && isInMap;
        }
        // Moyenne des notes
        if (range && range.length === 2) {
          isInRange = restaurant.avgRating >= range[0] && restaurant.avgRating <= range[1];
          shouldBeVisible = shouldBeVisible && isInRange;
        }

        return shouldBeVisible;
      });
    },
    setBoundsValue: (state, bounds) => {
      state.boundsValue = bounds;
    },
    setSortValue: (state, range) => {
      state.sortValue = range;
    },
    // Ajoute un restaurant en ajoutant automatiquement un champ avgRating et un ID (le dernier +1)
    addRestaurant: (state, { newRestaurant }) => {

      const ratings = newRestaurant.ratings || []

      const restaurantToAdd = {
        ...newRestaurant,
        ratings,
        avgRating: computeAvgRatings(ratings),
        ID: getLastId()
      }

      state.restaurantList.push(restaurantToAdd)
      state.visibleRestaurant.push(restaurantToAdd)

      function getLastId() {
        const lastId = state.restaurantList.reduce((acc, restaurant) => {
          if (acc < restaurant.ID) {
            return restaurant.ID
          }
          return acc
        }, 0)

        return lastId + 1
      }
    },
    // Ajoute un commentaire
    addComment: (state, {
      restaurantId,
      comment
    }) => {
      const restaurantIndex = getRestaurantIndex(state.restaurantList, restaurantId);

      state.restaurantList[restaurantIndex].ratings.push({
        ...comment
      })

      const restaurantRating = computeAvgRatings(state.restaurantList[restaurantIndex].ratings);
      state.restaurantList[restaurantIndex].avgRating = restaurantRating;
    }
  },
  // Fait appel à restaurantFactory et ajoute les restaurants de la liste JSON et de GooglePlaces
  actions: {
    getData: async function (context, { service, location }) {
      const restaurantList = await restaurantFactory.getRestaurantList(service, location)

      restaurantList.forEach((newRestaurant) => context.commit('addRestaurant', { newRestaurant }))
    },
  }
});

// Fonction helper pour getRestaurantById
function getRestaurantIndex(restaurantList, id) {
  return restaurantList
    .findIndex((restaurant) => restaurant.ID === parseInt(id))
}
// Fonction helper pour getRestaurantAvgRating
function computeAvgRatings (ratings) {
  const avgRating = ratings.reduce((acc, rating) => {
    return acc + (rating.stars / ratings.length);
  }, 0);
  return Math.round(avgRating);
}

А затем для карты я использую Google Places, как этот (компонент mainMap):

// Google Places
      setPlaces(location) {
        const service = new this.google.maps.places.PlacesService(this.map);
        // Appel l'action getData du Store
        this.$store.dispatch('getData', {
          service,
          location
        })
      }

Новые функции, над которыми я начал работать, находятся в комментарии в restaurantFactory.js

У меня появилась идея использовать getDetails для получения массива отзывов, используя place_id каждого ресторана.Я просто сейчас не знаю, как это реализовать.Благодаря.

...