我通过实现SuggestBox 的子类解决了这个问题,它有自己的SuggestOracle。 AddressOracle 用作 Google 地图服务的包装器,Google Maps API for GWT 中的 Geocoder 类为其提供抽象。
所以这是我的解决方案:
首先,我们为带有 Google 地图建议的 SuggestBox 实现小部件
public class GoogleMapsSuggestBox extends SuggestBox {
public GoogleMapsSuggestBox() {
super(new AddressOracle());
}
}
然后我们实现 SuggestOracle,它包装了 Geocoder 异步方法抽象:
class AddressOracle extends SuggestOracle {
// this instance is needed, to call the getLocations-Service
private final Geocoder geocoder;
public AddressOracle() {
geocoder = new Geocoder();
}
@Override
public void requestSuggestions(final Request request,
final Callback callback) {
// this is the string, the user has typed so far
String addressQuery = request.getQuery();
// look up for suggestions, only if at least 2 letters have been typed
if (addressQuery.length() > 2) {
geocoder.getLocations(addressQuery, new LocationCallback() {
@Override
public void onFailure(int statusCode) {
// do nothing
}
@Override
public void onSuccess(JsArray<Placemark> places) {
// create an oracle response from the places, found by the
// getLocations-Service
Collection<Suggestion> result = new LinkedList<Suggestion>();
for (int i = 0; i < places.length(); i++) {
String address = places.get(i).getAddress();
AddressSuggestion newSuggestion = new AddressSuggestion(
address);
result.add(newSuggestion);
}
Response response = new Response(result);
callback.onSuggestionsReady(request, response);
}
});
} else {
Response response = new Response(
Collections.<Suggestion> emptyList());
callback.onSuggestionsReady(request, response);
}
}
}
这是一个特殊的 oracle 建议类,它只代表一个带有交付地址的字符串。
class AddressSuggestion implements SuggestOracle.Suggestion, Serializable {
private static final long serialVersionUID = 1L;
String address;
public AddressSuggestion(String address) {
this.address = address;
}
@Override
public String getDisplayString() {
return this.address;
}
@Override
public String getReplacementString() {
return this.address;
}
}
现在您可以通过在EntryPoint-class 的onModuleLoad()-方法中编写以下行来将新小部件绑定到您的网页:
RootPanel.get("hm-map").add(new GoogleMapsSuggestBox());