Esempio n. 1
0
 /**
  * Get the polyline through a given geocode address
  *
  * @param placemark {@link Placemark} = the geocode address
  * @return {@link Polyline}
  */
 public Polyline getPolyline(Placemark placemark) {
   LatLng ne =
       LatLng.newInstance(
           placemark.getExtendedData().getBounds().getNorthEast().getLatitude(),
           placemark.getExtendedData().getBounds().getNorthEast().getLongitude());
   LatLng se =
       LatLng.newInstance(
           placemark.getExtendedData().getBounds().getSouthWest().getLatitude(),
           placemark.getExtendedData().getBounds().getNorthEast().getLongitude());
   LatLng sw =
       LatLng.newInstance(
           placemark.getExtendedData().getBounds().getSouthWest().getLatitude(),
           placemark.getExtendedData().getBounds().getSouthWest().getLongitude());
   LatLng nw =
       LatLng.newInstance(
           placemark.getExtendedData().getBounds().getNorthEast().getLatitude(),
           placemark.getExtendedData().getBounds().getSouthWest().getLongitude());
   LatLng[] latLngs = new LatLng[4];
   latLngs[0] = ne;
   latLngs[1] = se;
   latLngs[2] = sw;
   latLngs[3] = nw;
   Polyline polyline = new Polyline(latLngs, "#ff0000", 2, 1.0);
   return polyline;
 }
Esempio n. 2
0
  public static void handleDevMapClick(LatLng position) {
    if (WindowInformation.locationPanel.isRoadMode()) {
      if (location1ID != -1 && position != null) {
        roadPoints.add(position);
        // Window.alert("Road point added");
      }
    } else {
      String locationName = Window.prompt("Name for this location:", "NULL" + locationCounter++);
      if (locationName != null) {
        GameServices.devService.createLocation(
            GameInfo.getInstance().getPlayer(),
            locationName,
            position.getLatitude(),
            position.getLongitude(),
            new AsyncCallback<Void>() {
              public void onFailure(Throwable caught) {}

              public void onSuccess(Void result) {
                // TODO: Keep the auto-refresh when creating locations?
                // GameInformation.getInstance().refreshAll(true);
              }
            });
      }
    }
  }
 /** @param event */
 public void onMapClick(MapClickEvent event) {
   LatLng e = event.getLatLng();
   if (e == null) {
     e = event.getOverlayLatLng();
     //			if(mState == State.Default)
     //			{
     //				MapItemOverlay mio = (MapItemOverlay) event.getOverlay();
     //				HasCoordinates item = mio.getMapItem();
     //				if(item instanceof MapItem)
     //					showMapItemEdit((MapItem)item);
     //			}
   }
   if (mState == State.Adding || mState == State.Editing) {
     mDataModel.getX().setValue(e.getLongitude());
     mDataModel.getY().setValue(e.getLatitude());
     mDisplay.getStreetView().setLocation(e);
     handleChangePosition(e);
   } else if (mState == State.AddingStar) {
     Star s = new Star();
     s.setType(mStarType);
     s.setX(e.getLongitude());
     s.setY(e.getLatitude());
     onFinishAddingStar(s);
   }
 }
  private static LatLngBounds getSearchBoundsAsLatLngBounds(double radius) {

    CoordinateBounds bounds = getSearchBounds(radius);

    LatLngBounds b = LatLngBounds.newInstance();
    b.extend(LatLng.newInstance(bounds.getMinLat(), bounds.getMinLon()));
    b.extend(LatLng.newInstance(bounds.getMaxLat(), bounds.getMaxLon()));
    return b;
  }
  private static CoordinateBounds getSearchBounds(double radius) {

    LocationManager locationManager = MobileApplicationContext.getLocationManager();
    LatLng p = locationManager.getCurrentSearchLocation();

    CoordinateBounds bounds =
        SphericalGeometryLibrary.bounds(p.getLatitude(), p.getLongitude(), radius);
    System.out.println(bounds);
    return bounds;
  }
Esempio n. 6
0
  /** Run the query and load the map */
  public void runQuery() {
    String query = queryTextBox.getValue();
    if (isValidQuery(query)) {
      LatLng latlng = parseLatLng(query);
      if (latlng == null) {
        queryTextBox.setValue("");
      } else {
        Geocoder geocoder = new Geocoder();
        latlng = parseLatLng(latlng.toUrlValue(6));
        if (latlng != null) initMap(map.getElement(), latlng);
        else initMap(map.getElement(), LatLng.newInstance(0.0, 0.0));
        geocoder.getLocations(
            query,
            new LocationCallback() {
              @Override
              public void onFailure(int statusCode) {
                // Window.alert("failed");
                Document.get().getElementById("responseCount").getStyle().setDisplay(Display.NONE);
                Document.get().getElementById("matches").getStyle().setDisplay(Display.NONE);
              }

              @Override
              public void onSuccess(JsArray<Placemark> locations) {
                responseGeocode(locations, true);
              }
            });
      }
    } else {
      initMap(map.getElement(), LatLng.newInstance(0.0, 0.0));
      Geocoder geocoder = new Geocoder();
      // map.setUIToDefault();
      geocoder.getLocations(
          query,
          new LocationCallback() {
            @Override
            public void onFailure(int statusCode) {
              // Window.alert("failed");
              Document.get().getElementById("responseCount").getStyle().setDisplay(Display.NONE);
              Document.get().getElementById("matches").getStyle().setDisplay(Display.NONE);
            }

            @Override
            public void onSuccess(JsArray<Placemark> locations) {
              responseGeocode(locations, false);
            }
          });
    }
  }
 /**
  * Creates a 300x300 pixel map centered on Atlanta and adds it to the page.
  *
  * @return the created MapWidget instance.
  */
 protected MapWidget addDefaultMap() {
   LatLng atlanta = LatLng.newInstance(33.7814790, -84.3880580);
   MapWidget map = new MapWidget(atlanta, 8);
   map.setSize("300px", "300px");
   RootPanel.get().add(map);
   return map;
 }
Esempio n. 8
0
  public Geocoder2Demo() {
    Panel panel = new FlowPanel();
    final FormPanel form = new FormPanel();
    form.setAction("#");
    Panel formElements = new FlowPanel();
    Label label = new Label("Search for an address:");
    formElements.add(label);
    final TextBox addressBox = new TextBox();
    addressBox.setVisibleLength(40);
    formElements.add(addressBox);
    Button submit = new Button("Search");
    submit.addClickListener(
        new ClickListener() {
          public void onClick(Widget sender) {
            form.submit();
          }
        });
    formElements.add(submit);
    form.add(formElements);
    form.addFormHandler(
        new FormHandler() {
          public void onSubmit(FormSubmitEvent event) {
            showAddress(addressBox.getText());
            event.setCancelled(true);
          }

          public void onSubmitComplete(FormSubmitCompleteEvent event) {}
        });
    panel.add(form);

    map = new MapWidget(LatLng.newInstance(34, 0), 1);
    map.setSize("100%", "480px");
    panel.add(map);

    Grid grid = new Grid((sampleAddresses.length / NUM_ADDRESS_COLUMNS) + 1, NUM_ADDRESS_COLUMNS);

    for (int i = 0; i < sampleAddresses.length; i++) {
      final String address = sampleAddresses[i];
      Button link = new Button(address);
      // Hyperlink link = new Hyperlink(address, true,
      // "Extracting Structured Address Information");
      link.addClickListener(
          new ClickListener() {
            public void onClick(Widget sender) {
              addressBox.setText(address);
              form.submit();
            }
          });
      grid.setWidget(i / NUM_ADDRESS_COLUMNS, i % NUM_ADDRESS_COLUMNS, link);
    }
    panel.add(grid);

    initWidget(panel);
    geocoder = new Geocoder();
  }
Esempio n. 9
0
 /** Method allowing to display the map points associated to the authenticated user */
 private void displayUserMapPoints() {
   clearMapMarkers();
   if (Session.isAuthenticatedUser) {
     User authenticatedUser = Session.authenticatedUser;
     if (null != authenticatedUser) {
       for (UserPoint userPoint : authenticatedUser.getUserPoints()) {
         LatLng latLng = LatLng.newInstance(userPoint.getLatitude(), userPoint.getLongitude());
         map.addOverlay(prepareMarker(latLng));
       }
     }
   }
 }
Esempio n. 10
0
 /** Method to initialize our map */
 private void initializeMap() {
   // center the map around Paris
   LatLng parisCity = LatLng.newInstance(48.856614, 2.3522219);
   map = new MapWidget(parisCity, 5);
   map.setSize("100%", "100%");
   map.addControl(new LargeMapControl());
   map.setDoubleClickZoom(false);
   map.setCenter(parisCity);
   map.getInfoWindow().open(map.getCenter(), new InfoWindowContent("Paris, capitale de France"));
   addMapClickHandler();
   addMapDoubleClickHandler();
   layoutPanel.addNorth(map, 500);
 }
  /** Handle a map click event */
  public void onClick(final MapClickEvent e) {
    final MapWidget sender = e.getSender();
    final Overlay overlay = e.getOverlay();
    final LatLng point = e.getLatLng();

    if (overlay != null && overlay instanceof Marker) {
      // clear a marker that has been clicked on
      sender.removeOverlay(overlay);
    } else {
      // clear the last-placed marker ...
      if (_lastMarker != null && _lastMarker instanceof Marker) {
        sender.removeOverlay(_lastMarker);
        _lastMarker = null;
      }

      // ... and add the new marker
      final Marker mark = new Marker(point);
      _lastMarker = mark;
      sender.addOverlay(mark);

      // set the location
      new GeoFixAsyncCallback(point.getLatitude(), point.getLongitude()).execute();
    }
  }
  /** Initialize the UI */
  private void buildUi() {
    // Create a textbox and set default port
    _text = new TextBox();
    _text.setText(String.valueOf(DEFAULT_PORT));
    // Create button to change default port
    _button = new Button("Change Emulator Port");
    // Create the info/status label
    _info = new InlineLabel();

    // register the button action
    _button.addClickHandler(
        new ClickHandler() {
          public void onClick(final ClickEvent event) {
            final int port = Integer.valueOf(_text.getText());
            new PortAsyncCallback(port).execute();
          }
        });

    // Open a map centered on Cawker City, KS USA
    final LatLng cawkerCity = LatLng.newInstance(39.509, -98.434);
    final MapWidget map = new MapWidget(cawkerCity, 2);
    map.setSize("100%", "100%");

    // Workaround for bug with click handler & setUItoDefaults() - see issue 260
    final MapUIOptions opts = map.getDefaultUI();
    opts.setDoubleClick(false);
    map.setUI(opts);

    // Register map click handler
    map.addMapClickHandler(this);

    // Create panel for textbox, button and info label
    final FlowPanel div = new FlowPanel();
    div.add(_text);
    div.add(_button);
    div.add(_info);
    // Dock the map
    final DockLayoutPanel dock = new DockLayoutPanel(Unit.PX);
    dock.addNorth(map, 500);

    // Add the map dock to the div panel
    div.add(dock);
    RootLayoutPanel.get().add(div);
  }
  /**
   * Test when user add new icon, after that repeats click on icon and chaotic click on map to move
   * editing icon At the end is succ finish => icon should be at the last click position
   */
  private void tstClickOnMapEditingAndFinish() {
    // simple add and finish adding of new item
    map.clearOverlays();
    mapAddOverlayEvents.clear();
    mapRemoveOverlayEvents.clear();
    MapControllerT mc = new MapControllerT(map, service);
    mc.startAdding();
    LatLng ll1 = getRandomLatLng();
    mc.onMapClick(new MapClickEvent(map, null, ll1, null));
    mc.finishWorking(false);

    // now presenter is calling web service to save and after succ. save is called onAddItem
    MapItem mapItem = RandomGenerator.genMapItem(false);
    LatLng mapItemLatLng = LatLng.newInstance(mapItem.getY(), mapItem.getX());
    mc.addMapItem(mapItem);
    MapItemOverlay<MapItem> mi = (MapItemOverlay<MapItem>) mapAddOverlayEvents.get(1).getOverlay();
    DataComparator.assertEquals(mapItemLatLng, mi.getLatLng());

    // simulate click on icon
    mc.startEditing(mi);

    LatLng ll = null;
    for (int i = 0; i < 10; i++) // just chaotic click, icon should moves
    {
      ll = getRandomLatLng();
      mc.onMapClick(new MapClickEvent(map, null, ll, null));
      DataComparator.assertEquals(ll, mi.getLatLng());
      DataComparator.assertEquals(mapItemLatLng, mc.mStartEditLatLng);
    }

    mc.finishWorking(false); // finished => not canceled
    assertEquals(mc.mState, State.Default);
    assertNull(mc.mCurrentMarker);
    assertNull(mc.mStartEditLatLng);
    // after finish nothing should happen
    assertEquals(1, mc.mCurrentVisibleMapItems.size());
    assertEquals(2, mapAddOverlayEvents.size());
    assertEquals(1, mapRemoveOverlayEvents.size());
    // only editing icon should be at the last click position
    DataComparator.assertEquals(ll, mi.getLatLng());
  }
  private void setPosition(
      ExtSensor positionSensor,
      final List<ExtDevice> devices,
      final int index,
      final String name,
      final int floors,
      final Polygon outline,
      final List<ExtSensor> sensors) {

    ExtDevice device = devices.get(index);
    LatLng latLng = device.<LatLng>get("latlng");

    // prepare request properties
    final Method method = RequestBuilder.POST;
    final UrlBuilder urlBuilder =
        new UrlBuilder()
            .setProtocol(CommonSenseClient.Urls.PROTOCOL)
            .setHost(CommonSenseClient.Urls.HOST);
    urlBuilder.setPath(Urls.PATH_SENSORS + "/" + positionSensor.getId() + "/data.json");
    final String url = urlBuilder.buildString();
    final String sessionId = SessionManager.getSessionId();

    String value =
        "{\\\"latitude\\\":"
            + latLng.getLatitude()
            + ",\\\"longitude\\\":"
            + latLng.getLongitude()
            + ",\\\"provider\\\":\\\"environment\\\"}";
    String body = "{\"data\":[";
    body +=
        "{\"value\":\""
            + value
            + "\",\"date\":"
            + NumberFormat.getFormat("#.#").format(System.currentTimeMillis() / 1000)
            + "}";
    body += "]}";

    // prepare request callback
    RequestCallback reqCallback =
        new RequestCallback() {

          @Override
          public void onError(Request request, Throwable exception) {
            LOG.warning("POST position onError callback: " + exception.getMessage());
            onSetPositionFailure();
          }

          @Override
          public void onResponseReceived(Request request, Response response) {
            LOG.finest("POST position response received: " + response.getStatusText());
            int statusCode = response.getStatusCode();
            if (Response.SC_CREATED == statusCode) {
              onSetPositionSuccess(
                  response.getText(), devices, index, name, floors, outline, sensors);
            } else {
              LOG.warning("POST position returned incorrect status: " + statusCode);
              onSetPositionFailure();
            }
          }
        };

    // send request
    try {
      RequestBuilder builder = new RequestBuilder(method, url);
      builder.setHeader("X-SESSION_ID", sessionId);
      builder.setHeader("Content-Type", "application/json");
      builder.sendRequest(body, reqCallback);
    } catch (Exception e) {
      LOG.warning("POST position request threw exception: " + e.getMessage());
      reqCallback.onError(null, e);
    }
  }
  private void createEnvironment(
      String name, int floors, Polygon outline, final List<ExtSensor> sensors) {

    // create GPS outline String
    String gpsOutline = "";
    for (int i = 0; i < outline.getVertexCount(); i++) {
      LatLng vertex = outline.getVertex(i);
      gpsOutline += vertex.toUrlValue() + ";";
    }
    gpsOutline = gpsOutline.substring(0, gpsOutline.length() - 1);

    // create GPS position String
    String position = outline.getBounds().getCenter().toUrlValue();

    // prepare request properties
    final Method method = RequestBuilder.POST;
    final UrlBuilder urlBuilder =
        new UrlBuilder()
            .setProtocol(CommonSenseClient.Urls.PROTOCOL)
            .setHost(CommonSenseClient.Urls.HOST);
    urlBuilder.setPath(Urls.PATH_ENVIRONMENTS + ".json");
    final String url = urlBuilder.buildString();
    final String sessionId = SessionManager.getSessionId();

    String body = "{\"environment\":{";
    body += "\"" + ExtEnvironment.NAME + "\":\"" + name + "\",";
    body += "\"" + ExtEnvironment.FLOORS + "\":" + floors + ",";
    body += "\"" + ExtEnvironment.OUTLINE + "\":\"" + gpsOutline + "\",";
    body += "\"" + ExtEnvironment.POSITION + "\":\"" + position + "\"}";
    body += "}";

    // prepare request callback
    RequestCallback reqCallback =
        new RequestCallback() {

          @Override
          public void onError(Request request, Throwable exception) {
            LOG.warning("POST environments onError callback: " + exception.getMessage());
            onCreateEnvironmentFailure();
          }

          @Override
          public void onResponseReceived(Request request, Response response) {
            LOG.finest("POST environments response received: " + response.getStatusText());
            int statusCode = response.getStatusCode();
            if (Response.SC_CREATED == statusCode) {
              onCreateEnvironmentSuccess(response.getText(), sensors);
            } else {
              LOG.warning("POST environments returned incorrect status: " + statusCode);
              onCreateEnvironmentFailure();
            }
          }
        };

    // send request
    try {
      RequestBuilder builder = new RequestBuilder(method, url);
      builder.setHeader("X-SESSION_ID", sessionId);
      builder.setHeader("Content-Type", "application/json");
      builder.sendRequest(body, reqCallback);
    } catch (Exception e) {
      LOG.warning("POST environments request threw exception: " + e.getMessage());
      reqCallback.onError(null, e);
    }
  }
  @Override
  public void onModuleLoad() {

    HistoryContextManager manager = new HistoryContextManager();

    ModelEventsSourceAndSink events = new ModelEventsImpl();
    ModelEventSourceAndSink<LocationQueryModel> locationQueryModelEvents =
        events.getEventSourceAndSink(LocationQueryModel.class);
    ModelEventSourceAndSink<QueryModel> queryModelEvents =
        events.getEventSourceAndSink(QueryModel.class);
    ModelEventSourceAndSink<ResultsModel> resultsModelEvents =
        events.getEventSourceAndSink(ResultsModel.class);
    ModelEventSourceAndSink<FilteredResultsModel> filteredResultsModelEvents =
        events.getEventSourceAndSink(FilteredResultsModel.class);
    ModelEventSourceAndSink<StateEvent> stateEvents =
        events.getEventSourceAndSink(StateEvent.class);

    /** Model Layer */
    QueryModel queryModel = new QueryModel();
    queryModel.setEventSink(locationQueryModelEvents);
    queryModel.setQueryModelEventSink(queryModelEvents);

    TimedRegionModel timedRegionModel = new TimedRegionModel();
    TimedPolygonModel timedPolygonModel = new TimedPolygonModel();

    ResultsModel resultsModel = new ResultsModel();
    resultsModel.setEvents(resultsModelEvents);

    FilteredResultsModel filteredResultsModel = new FilteredResultsModel();
    filteredResultsModel.setResultsModel(resultsModel);
    filteredResultsModel.setEvents(filteredResultsModelEvents);

    PagedResultsModel pagedResultsModel = new PagedResultsModel();
    pagedResultsModel.setModel(filteredResultsModel);
    pagedResultsModel.setEvents(stateEvents);

    TripPlanModel tripModel = new TripPlanModel();

    /** Control Layer */
    YelpLocalSearchProvider localSearchProvider =
        new YelpLocalSearchProvider("VJYMvEAOfkqDeyHh4C9gTg");
    localSearchProvider.setTimeout(10000);

    MapOverlayManager mapOverlayManager = new MapOverlayManager();

    MinTransitTimeResultHandler minTransitTimeHandler = new MinTransitTimeResultHandler();
    minTransitTimeHandler.setMapOverlayManager(mapOverlayManager);
    // minTransitTimeHandler.setTimedRegionModel(timedRegionModel);
    minTransitTimeHandler.setTimedPolygonModel(timedPolygonModel);

    OneBusAwayStandardControlImpl control = new OneBusAwayStandardControlImpl();
    control.setStateEvents(stateEvents);

    // Models
    control.setQueryModel(queryModel);
    control.setResultsModel(resultsModel);
    control.setFilteredResultsModel(filteredResultsModel);
    control.setPagedResultsModel(pagedResultsModel);
    control.setTripPlanModel(tripModel);
    // Controls
    control.setLocalSearchProvider(localSearchProvider);
    control.setMinTransitTimeResultHandler(minTransitTimeHandler);

    control.setContextManager(manager);

    minTransitTimeHandler.setControl(control);

    /** View Layer */
    MapWidget mapWidget = new MapWidget(LatLng.newInstance(47.601533, -122.32933), 11);
    mapWidget.addControl(new LargeMapControl());
    mapWidget.addControl(new MapTypeControl());
    mapWidget.addControl(new ScaleControl());

    ColorGradientControl colorGradient = new ColorGradientControl();
    mapWidget.addControl(colorGradient);

    mapOverlayManager.setMapWidget(mapWidget);

    SearchWidget searchWidget = new SearchWidget();
    searchWidget.setControl(control);
    searchWidget.setMapWidget(mapWidget);

    WelcomePagePresenter welcome = new WelcomePagePresenter();

    AddressLookupPresenter addressLookup = new AddressLookupPresenter();
    addressLookup.setControl(control);

    ResultsFilterPresenter filter = new ResultsFilterPresenter();
    filter.setControl(control);

    ResultsTablePresenter resultsTable = new ResultsTablePresenter();
    resultsTable.setControl(control);
    resultsTable.setResultsModel(pagedResultsModel);
    resultsTable.setMapOverlayManager(mapOverlayManager);
    resultsTable.setResultsFilterWidget(filter.getWidget());

    CustomTimedOverlayManager timedOverlayManager = new CustomTimedOverlayManager();
    timedOverlayManager.setMapOverlayManager(mapOverlayManager);
    timedOverlayManager.setQueryModel(queryModel);
    timedOverlayManager.setColorGradientControl(colorGradient);

    CustomTripPlanResultTablePresenter plansWidget = new CustomTripPlanResultTablePresenter();
    plansWidget.setMapWidget(mapWidget);

    ActiveResultPresenter activeResult = new ActiveResultPresenter();
    activeResult.setMapOverlayManager(mapOverlayManager);
    activeResult.setControl(control);

    MainPage mainPage = new MainPage();
    mainPage.setControl(control);
    mainPage.setMapWidget(mapWidget);
    mainPage.setSearchWidget(searchWidget);
    mainPage.addResultsPanelWidget(welcome.getWidget());
    mainPage.addResultsPanelWidget(addressLookup.getWidget());
    mainPage.addResultsPanelWidget(resultsTable.getWidget());
    mainPage.addResultsPanelWidget(activeResult.getWidget());
    mainPage.addResultsPanelWidget(plansWidget.getWidget());

    manager.addContextListener(mainPage);

    SearchOriginMapPresenter searchOriginMapMarker = new SearchOriginMapPresenter();
    searchOriginMapMarker.setMapOverlayManager(mapOverlayManager);
    searchOriginMapMarker.setLocationQueryModel(queryModel);

    /** Wire up all the listeners */
    timedRegionModel.addModelListener(timedOverlayManager.getRegionModelListener());
    timedPolygonModel.addModelListener(timedOverlayManager.getPolygonModelListener());

    locationQueryModelEvents.addModelListener(control.getQueryModelHandler());
    queryModelEvents.addModelListener(searchWidget.getQueryModelHandler());

    resultsModelEvents.addModelListener(filteredResultsModel.getResultsModelHandler());
    resultsModelEvents.addModelListener(filter.getResultsModelHandler());

    filteredResultsModelEvents.addModelListener(pagedResultsModel.getModelListener());

    tripModel.addModelListener(plansWidget);

    stateEvents.addModelListener(welcome.getStateEventListener());
    stateEvents.addModelListener(resultsTable);
    stateEvents.addModelListener(activeResult);
    stateEvents.addModelListener(searchOriginMapMarker);
    stateEvents.addModelListener(plansWidget.getStateEventHandler());
    stateEvents.addModelListener(timedOverlayManager.getStateEventHandler());
    stateEvents.addModelListener(addressLookup.getStateEventListener());

    StyleInjector.inject(OneBusAwayStandardResources.INSTANCE.getCss().getText());
    StyleInjector.inject(TripPlannerResources.INSTANCE.getCss().getText());
    StyleInjector.inject(CommonResources.INSTANCE.getApplicationCss().getText());

    mainPage.initialize();
    StandardApplicationContainer.add(mainPage);
    mainPage.onContextChanged(manager.getContext());
  }
Esempio n. 17
0
  public GeoStory() {
    panel = new SplitLayoutPanel();
    types = new GeoEventTypes();
    model = new GeoStoryModel(types);
    space = new Space(LatLng.newInstance(45.50, -73.60), 4, types, model);
    time = new TimeLine(model, types);
    list = new ListBox(true);
    list.setVisibleItemCount(20);
    for (GeoStoryItem i : model.getItems()) {
      list.addItem(i.toString());
    }
    {
      controls = new VerticalPanel();
      {
        email = new TextBox();
        email.setText("*****@*****.**");
        controls.add(email);
        email.addChangeHandler(
            new ChangeHandler() {
              @Override
              public void onChange(ChangeEvent event) {}
            });
      }
      {
        Button getFromServer = new Button("Get from server");
        getFromServer.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                types.getEventFromServer.shareEvent(getEmail());
              }
            });
        controls.add(getFromServer);
      }
      {
        Button dump = new Button("Json dump");
        dump.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                StringBuilder sb = new StringBuilder();
                for (GeoStoryItem item : model.getItems()) {
                  sb.append(item.toJSON() + "\n");
                }
                DialogBox db = new DialogBox(true);
                TextArea ta = new TextArea();
                ta.setEnabled(true);
                ta.setText(sb.toString());
                db.add(ta);
                db.center();
                db.show();
              }
            });
        controls.add(dump);
      }
      {
        Button jsonload = new Button("Json load");
        jsonload.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                Question<String> q = new ContentQuestion("Entrer la cha”ne JSON");
                final QPanel textContent = new QPanel(new Questionnaire(q));
                textContent.center();
                textContent.show();
                q.answerChannel()
                    .registerHandler(
                        new WHandler<String>() {
                          @Override
                          public void onEvent(WEvent<String> elt) {
                            String[] lines = elt.getElement().split("\n");
                            for (String item : lines) {
                              JSONValue json = JSONParser.parse(item);
                              JSONObject object = json.isObject();
                              GeoStoryItem gsi = GeoStoryItem.fromJSON(object);
                              types.itemAdded.shareEvent(gsi);
                              types.centerEvent.shareEvent(null);
                            }
                          }
                        });
              }
            });
        controls.add(jsonload);
      }
      {
        Button popRandom = new Button("Populate at random");
        controls.add(popRandom);
        popRandom.addClickHandler(
            new ClickHandler() {

              @Override
              public void onClick(ClickEvent event) {
                model.populateRandomly(10);
                types.centerEvent.shareEvent(null);
              }
            });
      }
      {
        Button popFromText = new Button("Populate from text");
        controls.add(popFromText);
        popFromText.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                Question<String> q = new ContentQuestion("Description des evenements");
                final QPanel textContent = new QPanel(new Questionnaire(q));
                textContent.center();
                textContent.show();
                q.answerChannel()
                    .registerHandler(
                        new WHandler<String>() {
                          @Override
                          public void onEvent(WEvent<String> elt) {
                            List<Triple<String, Interval, String>> res =
                                GeoStoryParser.parse(elt.getElement());
                            int delay = 0;
                            final Geocoder geo = new Geocoder();
                            for (final Triple<String, Interval, String> indiv : res) {
                              geodecode(geo, indiv, delay = delay + 100);
                            }
                            textContent.hide();
                          }
                        });
              }
            });
      }
      {
        Button cia = new Button("Draw borders");
        controls.add(cia);
        cia.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                for (final Polyline poly : CIA.segments(CIA.northamerica)) {
                  space.space.addOverlay(poly);
                }
                for (final Polyline poly : CIA.segments(CIA.europe)) {
                  space.space.addOverlay(poly);
                }
              }
            });
      }
      {
        Button family = new Button("Genealogy info");
        controls.add(family);
        family.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                Geocoder geo = new Geocoder();
                for (final Triple<String, Interval, String> indiv : Genea.people()) {
                  geodecode(geo, indiv, 100);
                }
              }
            });
      }
      {
        Button addOne = new Button("Add one");
        addOne.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                ContentQuestion desc = new ContentQuestion("Description?");
                WhenQuestion when = new WhenQuestion("Quand?");
                ContentQuestion plac = new ContentQuestion("Nom du lieu?");
                WhereQuestion wher = new WhereQuestion("Sur la carte?", plac.answerChannel());
                Questionnaire q = new Questionnaire(desc, when, plac, wher);
                QPanel tested = new QPanel(q);
                // tested.setSize("50%", "50%");
                q.answerChannel()
                    .registerHandler(
                        new WHandler<Map<String, String>>() {
                          @Override
                          public void onEvent(WEvent<Map<String, String>> elt) {
                            Map<String, String> map = elt.getElement();
                            // Window.alert("Questionnaire are  "+ elt.getElement().toString());
                            String[] coord = map.get("Sur la carte?").split("\\|");
                            // Window.alert("Questionnaire are  "+ elt.getElement().toString()+"
                            // "+Arrays.toString(coord));
                            LatLng ll =
                                LatLng.newInstance(
                                    Double.parseDouble(coord[0]),
                                    Double.parseDouble(coord[1])); // ;
                            String[] dates = map.get("Quand?").split("->");
                            Interval interval =
                                new Interval(
                                    WhenQuestion.dtf.parse(dates[0]),
                                    WhenQuestion.dtf.parse(dates[1]));
                            GeoStoryItem geo =
                                new GeoStoryItem(
                                    interval, map.get("Nom du lieu?"), ll, map.get("Description?"));
                            Window.alert(
                                "GeoStory "
                                    + geo
                                    + " "
                                    + Arrays.toString(dates)
                                    + " "
                                    + map.get("Quand?"));
                            types.itemAdded.shareEvent(geo);
                            types.centerEvent.shareEvent(null);
                          }
                        });
                tested.center();
                tested.show();
              }
            });
        controls.add(addOne);
      }
      {
        Button reset = new Button("Reset");
        reset.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                model.reset();
                types.centerEvent.shareEvent(null);
              }
            });
        controls.add(reset);
      }
      {
        final TextBox search = new TextBox();
        search.setTitle("Search");
        final Button go = new Button("go");
        go.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                Set<GeoStoryItem> itemsSet = model.getItems();
                // filtering
                if (search.getText() != null && !search.getText().isEmpty()) {
                  for (GeoStoryItem geoStoryItem : itemsSet) {
                    if (geoStoryItem.getDescription().contains(search.getText())) {
                      geoStoryItem.setVisible(true);
                    } else {
                      geoStoryItem.setVisible(false);
                    }
                  }
                }
                types.centerEvent.shareEvent(null);
              }
            });
        controls.add(go);
        controls.add(search);
      }
      {
        final Button removeFilter = new Button("remove filter");
        removeFilter.addClickHandler(
            new ClickHandler() {
              @Override
              public void onClick(ClickEvent event) {
                Set<GeoStoryItem> itemsSet = model.getItems();
                // filtering
                for (GeoStoryItem geoStoryItem : itemsSet) {
                  geoStoryItem.setVisible(true);
                }
                types.centerEvent.shareEvent(null);
              }
            });
        controls.add(removeFilter);
      }
      panel.addSouth(time, 150);
      panel.addWest(controls, 150);
      panel.add(space);
      Window.addResizeHandler(this);
    }
    this.initWidget(panel);
    // Short term timer to check and resize the badly initialized map.
    Timer t =
        new Timer() {
          public void run() {
            space.checkResizeAndCenter();
            time.init();
          }
        };
    t.schedule(1);
  }
 private void assertEquals(LatLng ll1, LatLng ll2) {
   assertEquals(ll1.getLatitude(), ll2.getLatitude());
   assertEquals(ll1.getLongitude(), ll2.getLongitude());
 }
 private LatLng getRandomLatLng() {
   return LatLng.newInstance(RandomGenerator.genRandomY(), RandomGenerator.genRandomX());
 }
public class StepwiseGeoGameEntryPoint implements EntryPoint {

  public interface ControlImageBundle extends ImageBundle {
    @Resource("minus2.png")
    AbstractImagePrototype minus();

    @Resource("center2.png")
    AbstractImagePrototype center();

    @Resource("plus2.png")
    AbstractImagePrototype plus();
  }

  private static class ImageZoomControl extends CustomControl {
    public ImageZoomControl() {
      super(new ControlPosition(ControlAnchor.TOP_RIGHT, 7, 7));
    }

    @Override
    protected Widget initialize(final MapWidget map) {
      ControlImageBundle imgBundle = GWT.create(ControlImageBundle.class);
      Image centerImage = imgBundle.center().createImage();
      Image zoomInImage = imgBundle.plus().createImage();
      Image zoomOutImage = imgBundle.minus().createImage();

      centerImage.addClickHandler(
          new ClickHandler() {
            public void onClick(ClickEvent event) {
              if (GameInfo.getInstance().getPlayer() != null) {
                //
                //	map.setCenter(MapUtil.toLatLng(GameInformation.getInstance().getPlayer().getCurrentLocation().getMapPosition()));
                map.setCenter(
                    LatLng.newInstance(
                        GameInfo.getInstance().getPlayer().getCurrentLocation().getLatitude(),
                        GameInfo.getInstance().getPlayer().getCurrentLocation().getLongitude()));
                //		        		map.setZoomLevel(9);
              }
            }
          });
      zoomInImage.addClickHandler(
          new ClickHandler() {
            public void onClick(ClickEvent event) {
              map.zoomIn();
            }
          });
      zoomOutImage.addClickHandler(
          new ClickHandler() {
            public void onClick(ClickEvent event) {
              map.zoomOut();
            }
          });

      Grid container = new Grid(4, 1);
      container.setWidget(0, 0, centerImage);
      container.setWidget(2, 0, zoomInImage);
      container.setWidget(3, 0, zoomOutImage);

      return container;
    }

    @Override
    public boolean isSelectable() {
      return false;
    }
  }

  private LatLng startLocation = LatLng.newInstance(26.771974, -4.523621);
  //	private LatLngBounds outside = LatLngBounds.newInstance(
  //			LatLng.newInstance(25.771974,-5.523621),
  //			LatLng.newInstance(27.771974,-3.523621));

  public static String titleString = "Geogame";
  public static String footerString =
      "Carnegie Mellon, Department of Psychology and Robotics Institute (C) 2009";

  /** Creates a new instance of MainEntryPoint */
  public StepwiseGeoGameEntryPoint() {}

  /**
   * The entry point method, called automatically by loading a module that declares an implementing
   * class as an entry-point
   */
  public void onModuleLoad() {

    // Define widget elements
    final DockPanel dock = new DockPanel();
    dock.setHorizontalAlignment(DockPanel.ALIGN_CENTER);
    dock.setBorderWidth(3);

    final Label titleLabel = new Label(titleString);
    final Label footerLabel = new Label(footerString);

    final TreasurePanel treasurePanel = new TreasurePanel();
    final LocationInfoPanel locationPanel = new LocationInfoPanel();
    final MapWidget map = new MapWidget(startLocation, 1);
    final LoginPanel loginPanel = new LoginPanel();
    final CommsPanel commsPanel = new CommsPanel();
    final AcceptPanel acceptPanel = new AcceptPanel();

    loginPanel.setWidth("200px");
    loginPanel.setHeight("600px");

    locationPanel.setWidth("150px");
    //		locationPanel.setHeight("800px");

    map.setSize("800px", "380px");
    map.setGoogleBarEnabled(false);
    map.setCurrentMapType(MapType.getSatelliteMap());
    map.setScrollWheelZoomEnabled(true);
    map.setPinchToZoom(true);

    final String refererURL = Document.get().getReferrer();

    ImageZoomControl izm = new ImageZoomControl();
    izm.initialize(map);
    map.addControl(izm);

    //		map.addMapMoveHandler(new MapMoveHandler() {
    //
    //			public void onMove(MapMoveEvent event) {
    //				LatLngBounds rect = map.getBounds();
    //				LatLng rectSize = rect.toSpan();
    //
    //				if (rect.getNorthEast().getLatitude() >= outside.getNorthEast().getLatitude()) {
    //					map.setCenter(LatLng.newInstance(
    //							outside.getNorthEast().getLatitude() - rectSize.getLatitude()/2,
    //							map.getCenter().getLongitude()
    //							));
    //				} else if (rect.getNorthEast().getLongitude() >= outside.getNorthEast().getLongitude()) {
    //					map.setCenter(LatLng.newInstance(
    //							map.getCenter().getLatitude(),
    //							outside.getNorthEast().getLongitude() - rectSize.getLongitude()/2
    //							));
    //				} else if (rect.getSouthWest().getLatitude() <= outside.getSouthWest().getLatitude()) {
    //					map.setCenter(LatLng.newInstance(
    //							outside.getSouthWest().getLatitude() + rectSize.getLatitude()/2,
    //							map.getCenter().getLongitude()
    //							));
    //				} else if (rect.getSouthWest().getLongitude() <= outside.getSouthWest().getLongitude()) {
    //					map.setCenter(LatLng.newInstance(
    //							map.getCenter().getLatitude(),
    //							outside.getSouthWest().getLongitude() + rectSize.getLongitude()/2
    //							));
    //				}
    //			}
    //		});

    //		map.addMapZoomEndHandler(new MapZoomEndHandler() {
    //
    //			public void onZoomEnd(MapZoomEndEvent event) {
    //				if (map.getZoomLevel() <= map.getBoundsZoomLevel(outside)) {
    //					map.setZoomLevel(map.getBoundsZoomLevel(outside) + 1);
    //				}
    //			}
    //		});
    //
    map.addMapZoomEndHandler(
        new MapZoomEndHandler() {
          public void onZoomEnd(MapZoomEndEvent event) {
            int minZoomLevel = 7;
            int maxZoomLevel = 10;

            if (map.getZoomLevel() > 1 && map.getZoomLevel() < minZoomLevel) {
              map.setZoomLevel(minZoomLevel);
            } else if (map.getZoomLevel() > 1 && map.getZoomLevel() > maxZoomLevel) {
              map.setZoomLevel(maxZoomLevel);
            }
            GameInfo.getInstance().refreshAll(false);
          }
        });

    map.addMapClickHandler(
        new MapClickHandler() {
          public void onClick(MapClickEvent event) {
            if (event.getOverlay() != null) {
              return;
              //					//Then the click was over an overlay
              //					if(event.getOverlay().getClass()==GGLocationOverlay.class) {
              //						//Then it is a location :D
              //						GGLocationOverlay locationOverlay = (GGLocationOverlay)event.getOverlay();
              //						LocationDTO location = locationOverlay.getLocation();
              //						if(WindowInformation.locationPanel.isCreateMode() &&
              // WindowInformation.locationPanel.isRoadMode()) {
              //							//Then we should handle it in development mode (to start/end a road)
              //							DevUtil.handleDevLocationClick(location);
              //						} else {
              //							//Then we should try to move to that location
              //							AsyncCallback<ActionResult> callback = new AsyncCallback<ActionResult>() {
              //								public void onFailure(Throwable caught) {
              //									Window.alert("Move failed - " + caught.getMessage());
              //								}
              //
              //								public void onSuccess(ActionResult result) {
              //									if(result.isSuccess()) {
              //										Window.alert(result.getMessage());
              //										GameInformation.getInstance().updateInformation(result.getPlayer(),
              // result.getMapInformation());
              //										MapUtil.refreshMap(false);
              //										WindowInformation.locationPanel.refresh();
              //										WindowInformation.treasurePanel.refresh();
              //									}
              //								}
              //							};
              //
              //	GameServices.gameService.moveToLocation(GameInformation.getInstance().getPlayer(),
              // location.getId(), callback);
              //						}
              //						return;
              //					}
            } else {
              // Then it is a click on any point on the map
              if (WindowInformation.locationPanel.isCreateMode()) {
                DevUtil.handleDevMapClick(event.getLatLng());
              }
            }
          }
        });

    dock.add(titleLabel, DockPanel.NORTH);
    dock.add(footerLabel, DockPanel.SOUTH);
    dock.add(loginPanel, DockPanel.EAST);
    dock.add(map, DockPanel.CENTER);

    RootPanel.get().add(dock);

    WindowInformation.dockPanel = dock;
    WindowInformation.loginPanel = loginPanel;
    WindowInformation.treasurePanel = treasurePanel;
    WindowInformation.locationPanel = locationPanel;
    WindowInformation.commsPanel = commsPanel;
    WindowInformation.acceptPanel = acceptPanel;
    WindowInformation.titleLabel = titleLabel;
    WindowInformation.footerLabel = footerLabel;
    WindowInformation.mapWidget = map;
    WindowInformation.refererURL = refererURL;

    String AMTVisitor = Window.Location.getParameter("AMTVisitor");

    if (AMTVisitor == "true") {
      WindowInformation.AMTVisitor = true;
    }

    //		WindowInformation.locationInformationWindow = new LocationInformationWindow();
    //		WindowInformation.tradeWindow = new TradeWindow();
    //		WindowInformation.locationInformationWindow.setVisible(true);
    //		WindowInformation.tradeWindow.setVisible(true);

    WindowInformation.loginPanel.select();
    WindowInformation.loginPanel.maybeLoginThroughCookies();
  }
}
  private void tstLoadData() {
    // simple add and finish adding of new item
    map.clearOverlays();
    mapAddOverlayEvents.clear();
    mapRemoveOverlayEvents.clear();

    MapControllerT mc = new MapControllerT(map, service);
    randomData = new ArrayList<MapItem>();
    int iterator = 0;
    for (; iterator < 20; iterator++) {
      MapItem mi = RandomGenerator.genMapItem(false);
      mi.setId(iterator); // init ids
      randomData.add(mi);
    }

    service.setOnGetListener(
        new MockDataServiceAsync.OnGetListener() {
          @Override
          public void get(
              String className, String filters, boolean deep, AsyncCallback<List<?>> callback) {}

          @Override
          public void get(
              String className,
              double x1,
              double x2,
              double y1,
              double y2,
              boolean deep,
              AsyncCallback<List<?>> callback) {
            callback.onSuccess(randomData);
          }

          @Override
          public void get(String className, AsyncCallback<List<?>> callback) {}
        });

    // simulate map drag move
    LatLngBounds llb =
        LatLngBounds.newInstance(LatLng.newInstance(0, 0), LatLng.newInstance(80, 80));
    mc.loadIcons(12, llb); // just ensure about good zoom limit
    assertTrue(mc.calledOnLoad); // should becalled
    mc.calledOnLoad = false;
    assertEquals(randomData.size(), mc.mCurrentVisibleMapItems.size()); // this icons should be here
    assertEquals(randomData.size(), mapAddOverlayEvents.size());

    // call again, no new icon should be added into map
    mc.loadIcons(12, llb); //
    assertTrue(mc.calledOnLoad); // should becalled
    mc.calledOnLoad = false;
    assertEquals(randomData.size(), mc.mCurrentVisibleMapItems.size()); // this icons should be here
    assertEquals(randomData.size(), mapAddOverlayEvents.size());

    // add 10 new icons into database simulates different db result depending on latlngbounds
    for (; iterator < 30; iterator++) {
      MapItem mi = RandomGenerator.genMapItem(false);
      mi.setId(iterator); // init ids
      randomData.add(mi);
    }

    // call again, only 10 news icon should be added into map
    mc.loadIcons(12, llb); //
    assertTrue(mc.calledOnLoad); // should becalled
    mc.calledOnLoad = false;
    assertEquals(randomData.size(), mc.mCurrentVisibleMapItems.size()); // this icons should be here
    assertEquals(randomData.size(), mapAddOverlayEvents.size());

    for (int i = 0; i < iterator; i++) {
      long l = i;
      // check added data, should be same
      assertTrue(mc.mCurrentVisibleMapItems.containsKey(l));
      MapItemOverlay<MapItem> mi =
          (MapItemOverlay<MapItem>) mapAddOverlayEvents.get(i).getOverlay();
      DataComparator.assertEquals(randomData.get(i), mi.getMapItem(), true);
      DataComparator.assertEquals(randomData.get(i), mi.getMapItem(), true);
    }
  }