Thursday, February 21, 2013

Marker GWT Maps V3 Single and Double ClickHandler


        GWT Maps V2 supports both single click and double click handler for a single marker in the same window. Whereas, in V3, both methods are available but only single click handler triggers if used for the same marker. In my scenario, I need single click handler for showing InfoWindow and double click handler to navigate to other page(another tab) within application. Normally if u want to implement both in maps V3, single click handler needs a delay or need some asynchronous calls. Here, I have used Geocoder in single click for getting address of particular marker(getting latlng) and showing in InfoWindow.

Sample Code for using both Handlers:

 VerticalPanel panel = new VerticalPanel();
  panel.setSize("1200", "800");
  LatLng myLatLng = LatLng.create(13.029603, 80.271800);
  MapOptions myOptions = MapOptions.create();
  myOptions.setZoom(8.0);
  myOptions.setCenter(myLatLng);
  myOptions.setScaleControl(true);
  myOptions.setMapTypeId(MapTypeId.ROADMAP);
  GoogleMap mapWidget = GoogleMap.create(panel.getElement(), myOptions);
  MarkerOptions newMarkerOpts = MarkerOptions.create();
  newMarkerOpts.setPosition(myLatLng);
  newMarkerOpts.setTitle("Hello World!");
  final Marker marker = Marker.create(newMarkerOpts);
  marker.setMap(mapWidget);
 marker.addClickListener(new ClickHandler() {
   @Override
   public void handle(MouseEvent event) {
    Geocoder geocoder = Geocoder.create();
    GeocoderRequest request = GeocoderRequest.create();
    request.setLocation(event.getLatLng());
    geocoder.geocode(request, new Callback() {
     @Override
     public void handle(JsArray<GeocoderResult> a,
       GeocoderStatus b) {
      if (b == GeocoderStatus.OK) {
       if (a.length() > 0) {
        GeocoderResult geocoderResult = a.get(0);
        StringBuffer sb = new StringBuffer();
        JsArray<GeocoderAddressComponent> addressComponents = geocoderResult
          .getAddressComponents();
        for (int i = 0; i < addressComponents.length(); i++) {
         if (i > 0) {
          sb.append(", ");
         }
         sb.append(addressComponents.get(i)
           .getLongName());
        }
        String location = sb.toString();
        InfoWindowOptions infoWindowOptions = InfoWindowOptions.create();
        infoWindowOptions.setContent(location);
        InfoWindow infoWindow = InfoWindow.create(infoWindowOptions);
        infoWindow.open(mapWidget, marker);
       }
      }
     }
    });
   }
  });
 
  marker.addDblClickListener(new DblClickHandler() {
   @Override
   public void handle(MouseEvent event) {
    Window.alert("Double Click Demo");
   }
  });