如何过滤 Google 个地点 getCurrentPlace 的结果?

How do I filter results from Google Places getCurrentPlace?

我正在使用 Google Place 的 getCurrentPlace API 并希望将我的结果过滤到特定类型的地点。我该怎么做?

虽然 getCurrentPlace 确实采用过滤器参数,但该过滤器非常受限 - 它仅允许按现在营业的企业或特定地点 ID 进行过滤(如果您想按预定义位置列表进行过滤,则很有用)。在一个糟糕的设计中,这个 class 是最终的,所以你不能扩展它。您必须在调用他们的 API 后进行过滤。这有点浪费内存,但无法避免。

以下代码按类型过滤 PlaceLikelihoodBuffer。它允许您指定多个允许的类型和不允许的类型。不允许优先于允许 - 例如,如果您指定允许是餐馆,不允许是杂货店,它将拒绝杂货店中的任何咖啡馆。

package com.gabesechan.android.reusable.location;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class PlaceTypeFilter {

    private Set<Integer> mAllowedTypes;
    private Set<Integer> mDisallowedTypes;

    public PlaceTypeFilter(int allowedTypes[], int disallowedTypes[]) {
        mAllowedTypes = new HashSet<>();
        for(int type : allowedTypes) {
            mAllowedTypes.add(type);
        }
        mDisallowedTypes = new HashSet<>();
        for(int type : disallowedTypes) {
            mDisallowedTypes.add(type);
        }
    }

    public  boolean hasMatchingType(Place place) {
        List<Integer> types = place.getPlaceTypes();
        for (int type : types) {
            if (mDisallowedTypes.contains(type)) {
                return false;
            }
        }
        for (int type : types) {
            if (mAllowedTypes.contains(type)) {
                return true;
            }
        }
        return false;
    }

    public List<PlaceLikelihood> filteredPlaces(PlaceLikelihoodBuffer places) {
        List<PlaceLikelihood> results = new ArrayList<>();
        for(PlaceLikelihood likelihood : places) {
            if(hasMatchingType(likelihood.getPlace())) {
                results.add(likelihood);
            }
        }
        return results;
    }

}