Algolia - Places autocomplete using php api client

时间:2019-01-15 18:24:30

标签: algolia

I've been playing around with the Algolia autocomplete places.js library. When you use the library you get a list of suggestions e.g.

{
  "query": "pari",
  "suggestion": {
     "name": "Paris",
     "administrative": "Île-de-France",
     "country": "France",
     "countryCode": "fr",
     "type": "city",
     "latlng": {
     "lat": 48.8546,
     "lng": 2.34771
   },
  "postcode": "75000",
  "highlight": {
      "name": "<em>Pari</em>s",
      "administrative": "Île-de-France",
      "country": "France"
   },
   "value": "Paris, Île-de-France, France"
 }
}

I have a need to use the php client and return a list of suggestions for my own applications api e.g.

$places = \AlgoliaSearch\Client::initPlaces();

$result = $places->search($term, [

        'type' => ['city', 'country', 'address'],
        'language' => 'en',
        'aroundLatLngViaIP' => false,

]);

dd($result);

However when you use the php client (note I'm using laravel scout in this instance) you don't get a list of suggestions i.e. there is no value property (Full display name of the place found)in the response that you can return back to the end user - instead you end up with the following response?

 {
   "hits": [{
   "objectID": "145746683_7444",
      "locale_names": {
         "default": ["Paris"],
    },
   "city": {
       "default": ["Paris"],
    },
   "county": {
       "default": ["Paris"],
   },
   "administrative": ["Île-de-France"],
   "country": {
       "default": "France",
   },
   "country_code": "fr",
   "postcode": ["75000"],
   "population": 2243833,
   "_geoloc": {
       "lat": 48.8564,
       "lng": 2.3521
   },
   "_highlightResult": {
       "locale_names": {
          "default": [{
              "value": "<em>Paris</em>",
              "fullyHighlighted": true,
              "matchedWords": ["paris"],
              "matchLevel": "full"
          }]
     },

   }
 }],
 "nbHits": 1,
 "query": "Paris"
}

1 个答案:

答案 0 :(得分:0)

如果您查看Algolia Places JavaScript library,那么在将其交给自动完成功能之前,这也是他们正在处理的数据。

您应该在此代码中找到所需的所有内容,更具体地说,是找到的位置的完整显示名称,它是基于此构建的:

 const out = `${name}${type !== 'country' && country !== undefined ? ',' : ''}
 ${city ? `${city},` : ''}
 ${administrative ? `${administrative},` : ''}
 ${country ? country : ''}`
    .replace(/\s*\n\s*/g, ' ')
    .trim();
  return out;

(位于formatInputValue.js file`)