2011-12-12 162 views

回答

8

我通過實現SuggestBox的子類來解決這個問題,它有自己的SuggestOracleAddressOracle作爲Google地圖服務的封裝器處理,Google Maps API for GWT中的類Geocoder提供了抽象。

因此,這裏是我的解決方案:

首先我們實現控件與谷歌地圖的建議一SuggestBox

public class GoogleMapsSuggestBox extends SuggestBox { 
    public GoogleMapsSuggestBox() { 
     super(new AddressOracle()); 
    } 
} 

然後我們實行SuggestOracle,它包裝的地理編碼器異步方法抽象:

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建議的一個特殊類,它只是表示帶有地址的字符串。

RootPanel.get("hm-map").add(new GoogleMapsSuggestBox()); 

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; 
    } 
} 

現在,您可以通過編寫以下行onModuleLoad() - 方法您EntryPoint -class的結合新的小部件到您的網頁

相關問題