public Canvas getViewPanel() {
    VLayout layout = new VLayout();
    layout.setWidth100();
    layout.setHeight100();

    // Map with ID mapGeoTools is defined in the XML configuration. (mapGeoTools.xml)
    final MapWidget map = new MapWidget("mapGeoTools", "appGeoTools");
    // Select the layer, so we can also create features !
    map.getMapModel()
        .runWhenInitialized(
            new Runnable() {

              @Override
              public void run() {
                // select to create new features
                map.getMapModel().getLayer("clientLayerCountriesGeoTools").setSelected(true);
              }
            });

    // Set a panning controller on the map:
    map.setController(new PanController(map));
    // Create a tool-bar for this map:
    final Toolbar toolbar = new Toolbar(map);
    toolbar.setButtonSize(WidgetLayout.toolbarLargeButtonSize);

    layout.addMember(toolbar);
    layout.addMember(map);
    return layout;
  }
  @Override
  public void accept(PainterVisitor visitor, Object group, Bbox bounds, boolean recursive) {
    if (googleMap != null) {
      String sourceCrs = map.getMapModel().getCrs();
      if (isGoogleProjection(sourceCrs)) {
        int zoomLevel = calcZoomLevel(map.getMapModel().getMapView().getCurrentScale());
        Coordinate latLon = convertToLatLon(bounds.getCenterPoint());
        fitGoogleMapBounds(googleMap, latLon, zoomLevel);
      } else {
        // transform on server
        TransformGeometryRequest request = new TransformGeometryRequest();
        request.setBounds(
            new org.geomajas.geometry.Bbox(
                bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()));
        request.setSourceCrs(map.getMapModel().getCrs());
        request.setTargetCrs(EPSG_3857);
        GwtCommand command = new GwtCommand(TransformGeometryRequest.COMMAND);
        command.setCommandRequest(request);
        GwtCommandDispatcher.getInstance()
            .execute(
                command,
                new AbstractCommandCallback<TransformGeometryResponse>() {

                  public void execute(TransformGeometryResponse response) {
                    Bbox google = new Bbox(response.getBounds());
                    int zoomLevel = calcZoomLevelFromBounds(google);
                    fitGoogleMapBounds(
                        googleMap, convertToLatLon(google.getCenterPoint()), zoomLevel);
                  }
                });
      }
    }
  }
  private void draw(Geometry geometry) {
    org.geomajas.gwt.client.spatial.geometry.Geometry transformed =
        mapWidget
            .getMapModel()
            .getMapView()
            .getWorldViewTransformer()
            .worldToPan(GeometryConverter.toGwt(geometry));

    GraphicsContext graphics = mapWidget.getVectorContext();
    graphics.drawGroup(mapWidget.getGroup(RenderGroup.VECTOR), geometry);

    if (transformed instanceof MultiPolygon) {
      draw(geometry, null, (MultiPolygon) transformed, graphics);
    } else if (transformed instanceof MultiPoint) {
      draw(geometry, null, (MultiPoint) transformed, graphics);
    } else if (transformed instanceof MultiLineString) {
      draw(geometry, null, (MultiLineString) transformed, graphics);
    } else if (transformed instanceof Polygon) {
      draw(geometry, null, (Polygon) transformed, graphics);
    } else if (transformed instanceof LineString) {
      draw(geometry, null, (LineString) transformed, graphics);
    } else if (transformed instanceof Point) {
      draw(geometry, null, (Point) transformed, graphics);
    }
  }
 public void setVisible(boolean visible) {
   if (visible) {
     mapWidget.getVectorContext().hide(editingService.getGeometry());
   } else {
     mapWidget.getVectorContext().unhide(editingService.getGeometry());
   }
 }
  private void updateEdge(Geometry geometry, GeometryIndex index, boolean bringToFront)
      throws GeometryIndexNotFoundException {
    // Some initialization:
    String identifier = baseName + "." + editingService.getIndexService().format(index);
    Object parentGroup =
        groups.get(identifier.substring(0, identifier.lastIndexOf('.')) + ".edges");

    Coordinate[] c = editingService.getIndexService().getEdge(geometry, index);
    LineString temp = mapWidget.getMapModel().getGeometryFactory().createLineString(c);
    LineString edge =
        (LineString)
            mapWidget.getMapModel().getMapView().getWorldViewTransformer().worldToPan(temp);
    mapWidget.getVectorContext().drawLine(parentGroup, identifier, edge, findEdgeStyle(index));
  }
  @Override
  public void accept(PainterVisitor visitor, Object group, Bbox bounds, boolean recursive) {
    map.getVectorContext().drawGroup(group, this);
    adjustScale(map.getMapModel().getMapView().getCurrentScale());
    // Draw a dummy at 0,0 so that Internet Explorer knows where coordinate 0,0 is. If this is not
    // drawn, the text
    // will disappear, because the parent group will have coordinate 0,0 at the upper left corner of
    // the union of
    // all the rectangles that are drawn here.
    map.getVectorContext()
        .drawRectangle(this, dummy.getId(), dummy.getBounds(), (ShapeStyle) dummy.getStyle());

    map.getVectorContext()
        .drawRectangle(this, backGround.getId(), backGround.getBounds(), backGround.getStyle());
    map.getVectorContext()
        .drawRectangle(this, bottomLine.getId(), bottomLine.getBounds(), bottomLine.getStyle());
    map.getVectorContext()
        .drawRectangle(this, leftMarker.getId(), leftMarker.getBounds(), leftMarker.getStyle());
    map.getVectorContext()
        .drawRectangle(this, rightMarker.getId(), rightMarker.getBounds(), rightMarker.getStyle());
    map.getVectorContext()
        .drawText(
            this,
            distance.getId(),
            distance.getContent(),
            distance.getPosition(),
            distance.getStyle());
  }
  private void updateVertex(Geometry geometry, GeometryIndex index, boolean moveToBack)
      throws GeometryIndexNotFoundException {
    // Some initialization:
    String identifier = baseName + "." + editingService.getIndexService().format(index);
    Composite parentGroup =
        groups.get(identifier.substring(0, identifier.lastIndexOf('.')) + ".vertices");

    Coordinate temp = editingService.getIndexService().getVertex(geometry, index);
    Coordinate coordinate =
        mapWidget.getMapModel().getMapView().getWorldViewTransformer().worldToPan(temp);
    addShapeToGraphicsContext(
        mapWidget.getVectorContext(), parentGroup, identifier, coordinate, findVertexStyle(index));
    if (moveToBack) {
      mapWidget.getVectorContext().moveToBack(parentGroup, identifier);
    }
  }
  private void draw(
      Object parentGroup,
      GeometryIndex parentIndex,
      LinearRing linearRing,
      GraphicsContext graphics) {
    String groupName = baseName;
    if (parentIndex != null) {
      groupName += "." + editingService.getIndexService().format(parentIndex);
    }
    Composite edgeGroup = getOrCreateGroup(parentGroup, groupName + ".edges");
    Composite vertexGroup = getOrCreateGroup(parentGroup, groupName + ".vertices");

    Coordinate[] coordinates = linearRing.getCoordinates();
    if (coordinates != null) {
      // Check if we have to draw the background as well (if there are controllers defined for it):
      GraphicsController controller = createGeometryController(parentIndex);
      if (controller != null) {
        Polygon polygon =
            mapWidget.getMapModel().getGeometryFactory().createPolygon(linearRing, null);
        graphics.drawPolygon(parentGroup, groupName + ".background", polygon, new ShapeStyle());
        graphics.setController(parentGroup, groupName + ".background", controller);
      }

      // Draw individual edges:
      int max = coordinates.length;
      if (!styleService.isCloseRingWhileInserting()
          && editingService.getEditingState() == GeometryEditState.INSERTING
          && editingService
              .getIndexService()
              .isChildOf(parentIndex, editingService.getInsertIndex())) {
        max--;
      }
      for (int i = 1; i < max; i++) {
        GeometryIndex edgeIndex =
            editingService
                .getIndexService()
                .addChildren(parentIndex, GeometryIndexType.TYPE_EDGE, i - 1);
        String identifier = baseName + "." + editingService.getIndexService().format(edgeIndex);

        LineString edge =
            linearRing
                .getGeometryFactory()
                .createLineString(new Coordinate[] {coordinates[i - 1], coordinates[i]});
        graphics.drawLine(edgeGroup, identifier, edge, findEdgeStyle(edgeIndex));
        graphics.setController(edgeGroup, identifier, createEdgeController(edgeIndex));
      }

      addInivisibleShapeToGraphicsContext(graphics, vertexGroup);
      for (int i = 0; i < coordinates.length - 1; i++) {
        GeometryIndex vertexIndex =
            editingService
                .getIndexService()
                .addChildren(parentIndex, GeometryIndexType.TYPE_VERTEX, i);
        String identifier = baseName + "." + editingService.getIndexService().format(vertexIndex);
        addShapeToGraphicsContext(
            graphics, vertexGroup, identifier, coordinates[i], findVertexStyle(vertexIndex));
        graphics.setController(vertexGroup, identifier, createVertexController(vertexIndex));
      }
    }
  }
  public void onGeometryEditStart(GeometryEditStartEvent event) {
    // Also look at the map for changes in the MapView:
    mapViewRegistration = mapWidget.getMapModel().getMapView().addMapViewChangedHandler(this);

    // Render the geometry on the map:
    groups.clear();
    draw(event.getGeometry());
  }
 /**
  * Used in creating the "edges", "selection" and "vertices" groups for LineStrings and
  * LinearRings.
  */
 private Composite getOrCreateGroup(Object parent, String name) {
   if (groups.containsKey(name)) {
     return groups.get(name);
   }
   Composite group = new Composite(name);
   mapWidget.getVectorContext().drawGroup(parent, group);
   groups.put(name, group);
   return group;
 }
  public void onCoordinateSnapAttempt(CoordinateSnapEvent event) {
    if (editingService.getEditingState() == GeometryEditState.INSERTING) {
      String identifier =
          baseName + "." + editingService.getIndexService().format(editingService.getInsertIndex());
      Object parentGroup =
          groups.get(identifier.substring(0, identifier.lastIndexOf('.')) + ".vertices");

      Coordinate temp = event.getTo();
      Coordinate coordinate =
          mapWidget.getMapModel().getMapView().getWorldViewTransformer().worldToPan(temp);
      addShapeToGraphicsContext(
          mapWidget.getVectorContext(),
          parentGroup,
          identifier,
          coordinate,
          event.hasSnapped() ? styleService.getVertexSnappedStyle() : new ShapeStyle());
    }
  }
  public void onGeometryEditStop(GeometryEditStopEvent event) {
    // Remove the handler that follows changes in the map view:
    if (mapViewRegistration != null) {
      mapViewRegistration.removeHandler();
      mapViewRegistration = null;
    }

    // Cleanup the geometry from the map:
    groups.clear();
    mapWidget.getVectorContext().deleteGroup(event.getGeometry());
  }
  public void onChangeEditingState(GeometryEditChangeStateEvent event) {
    switch (event.getEditingState()) {
      case DRAGGING:
        mapWidget.setCursor(Cursor.MOVE);
        break;
      case IDLE:
      default:
        mapWidget.setCursorString(mapWidget.getDefaultCursorString());
        redraw();

        // Remove the temporary insert move line:
        if (editingService.getInsertIndex() != null) {
          String id =
              baseName
                  + "."
                  + editingService.getIndexService().format(editingService.getInsertIndex());
          Object parentGroup = groups.get(id.substring(0, id.lastIndexOf('.')) + ".edges");
          mapWidget.getVectorContext().deleteElement(parentGroup, insertMoveEdgeId1);
          mapWidget.getVectorContext().deleteElement(parentGroup, insertMoveEdgeId2);
        }
    }
  }
 @Override
 public void onDraw() {
   if (googleMap == null) {
     // create as first child of raster group
     map.getRasterContext().drawGroup(null, this);
     String id = map.getRasterContext().getId(this);
     // move to first position
     Element mapDiv = DOM.getElementById(id);
     Element rasterGroup =
         DOM.getElementById(map.getRasterContext().getId(map.getGroup(RenderGroup.RASTER)));
     DOM.insertBefore(DOM.getParent(rasterGroup), mapDiv, rasterGroup);
     String graphicsId = map.getVectorContext().getId();
     googleMap =
         createGoogleMap(
             id,
             graphicsId,
             type.name(),
             showMap,
             getVerticalMargin(),
             getHorizontalMargin(),
             getVerticalAlignmentString());
   }
 }
 private void moveTosCopyRight() {
   // move the ToS and copyright to the top
   // create a div group in the graphics context
   if (tosGroup == null) {
     String graphicsId = map.getVectorContext().getId();
     Element graphics = DOM.getElementById(graphicsId);
     tosGroup = DOM.createDiv();
     tosGroup.setId(map.getID() + "-googleAddon");
     tosGroup.getStyle().setBottom(VERTICAL_MARGIN, Unit.PX);
     graphics.appendChild(tosGroup);
     UIObject.setVisible(tosGroup, visible);
   }
   String mapsId = map.getRasterContext().getId(this);
   Element gmap = DOM.getElementById(mapsId);
   if (gmap.getChildCount() > 0) {
     Node baseMap = gmap.getChild(0);
     if (baseMap.getChildCount() > 2) {
       Node copyright = baseMap.getChild(1);
       Node tos = baseMap.getChild(2);
       tosGroup.appendChild(copyright);
       tosGroup.appendChild(tos);
     }
   }
 }
  // TODO make use of the findGeometryStyle method.
  private void updateGeometry(Geometry geometry, GeometryIndex index, boolean bringToFront)
      throws GeometryIndexNotFoundException {
    // Some initialization:
    String identifier = baseName + "." + editingService.getIndexService().format(index);
    boolean marked = editingService.getIndexStateService().isMarkedForDeletion(index);

    // Find current and previous parent groups:
    Composite parentGroup =
        groups.get(identifier.substring(0, identifier.lastIndexOf('.')) + ".geometries");

    // Find the correct style:
    ShapeStyle style = new ShapeStyle();
    if (marked) {
      style = styleService.getBackgroundMarkedForDeletionStyle();
    }

    // Draw the inner ring:
    org.geomajas.gwt.client.spatial.geometry.Geometry transformed =
        mapWidget
            .getMapModel()
            .getMapView()
            .getWorldViewTransformer()
            .worldToPan(
                GeometryConverter.toGwt(
                    editingService.getIndexService().getGeometry(geometry, index)));
    if (transformed instanceof LinearRing) {
      Polygon polygon =
          mapWidget
              .getMapModel()
              .getGeometryFactory()
              .createPolygon((LinearRing) transformed, null);
      mapWidget
          .getVectorContext()
          .drawPolygon(parentGroup, identifier + ".background", polygon, style);
    }
  }
 /**
  * Set the visibility of the Google map.
  *
  * @param visible
  * @since 1.9.0
  */
 @Api
 public void setVisible(boolean visible) {
   this.visible = visible;
   if (googleMap != null) {
     String mapsId = map.getRasterContext().getId(this);
     Element gmap = DOM.getElementById(mapsId);
     UIObject.setVisible(gmap, visible);
     if (tosGroup != null) {
       UIObject.setVisible(tosGroup, visible);
     }
     if (visible) {
       triggerResize(googleMap);
     }
   }
 }
  @Override
  public void onRemove() {
    String id = map.getRasterContext().getId(this);

    // Remove the terms of use:
    Element element = DOM.getElementById(id + "-googleAddon");
    if (element != null) {
      Element parent = DOM.getParent(element);
      parent.removeChild(element);
    }

    // Remove the Google map too:
    element = DOM.getElementById(id);
    if (element != null) {
      Element parent = DOM.getParent(element);
      parent.removeChild(element);
    }

    googleMap = null;
  }
  public void onGeometryEditMove(GeometryEditMoveEvent event) {

    // Find the elements that need updating:
    Map<GeometryIndex, Boolean> indicesToUpdate = new HashMap<GeometryIndex, Boolean>();
    for (GeometryIndex index : event.getIndices()) {
      if (!indicesToUpdate.containsKey(index)) {
        indicesToUpdate.put(index, false);
        if (!Geometry.POINT.equals(editingService.getGeometry().getGeometryType())
            && !Geometry.MULTI_POINT.equals(editingService.getGeometry().getGeometryType())) {
          try {
            List<GeometryIndex> neighbors = null;
            switch (editingService.getIndexService().getType(index)) {
              case TYPE_VERTEX:
                // Move current vertex to the back. This helps the delete operation.
                indicesToUpdate.put(index, true);
                neighbors =
                    editingService.getIndexService().getAdjacentEdges(event.getGeometry(), index);
                if (neighbors != null) {
                  for (GeometryIndex neighborIndex : neighbors) {
                    if (!indicesToUpdate.containsKey(neighborIndex)) {
                      indicesToUpdate.put(neighborIndex, false);
                    }
                  }
                }

                neighbors =
                    editingService
                        .getIndexService()
                        .getAdjacentVertices(event.getGeometry(), index);
                if (neighbors != null) {
                  for (GeometryIndex neighborIndex : neighbors) {
                    if (!indicesToUpdate.containsKey(neighborIndex)) {
                      indicesToUpdate.put(neighborIndex, false);
                    }
                  }
                }
                break;
              case TYPE_EDGE:
                neighbors =
                    editingService
                        .getIndexService()
                        .getAdjacentVertices(event.getGeometry(), index);
                if (neighbors != null) {
                  for (GeometryIndex neighborIndex : neighbors) {
                    if (!indicesToUpdate.containsKey(neighborIndex)) {
                      indicesToUpdate.put(neighborIndex, false);
                    }
                  }
                }
                break;
              default:
            }
          } catch (GeometryIndexNotFoundException e) {
            throw new IllegalStateException(e);
          }
        }
      }
    }

    // Check if we need to draw the background (nice, but slows down):
    if (styleService.getBackgroundStyle() != null
        && styleService.getBackgroundStyle().getFillOpacity() > 0) {
      if (event.getGeometry().getGeometryType().equals(Geometry.POLYGON)) {
        org.geomajas.gwt.client.spatial.geometry.Geometry transformed =
            mapWidget
                .getMapModel()
                .getMapView()
                .getWorldViewTransformer()
                .worldToPan(GeometryConverter.toGwt(event.getGeometry()));
        mapWidget
            .getVectorContext()
            .drawPolygon(
                groups.get(baseName + ".background"),
                "background",
                (Polygon) transformed,
                styleService.getBackgroundStyle());
      } else if (event.getGeometry().getGeometryType().equals(Geometry.MULTI_POLYGON)
          && event.getGeometry().getGeometries() != null) {
        for (int i = 0; i < event.getGeometry().getGeometries().length; i++) {
          Geometry polygon = event.getGeometry().getGeometries()[i];

          org.geomajas.gwt.client.spatial.geometry.Geometry transformed =
              mapWidget
                  .getMapModel()
                  .getMapView()
                  .getWorldViewTransformer()
                  .worldToPan(GeometryConverter.toGwt(polygon));
          mapWidget
              .getVectorContext()
              .drawPolygon(
                  groups.get(baseName + ".geometry" + i + ".background"),
                  "background",
                  (Polygon) transformed,
                  styleService.getBackgroundStyle());
        }
      }
    }

    // Next, redraw the list:
    for (GeometryIndex index : indicesToUpdate.keySet()) {
      update(event.getGeometry(), index, indicesToUpdate.get(index));
    }
  }
 private int calcZoomLevelFromBounds(Bbox google) {
   return calcZoomLevel(map.getWidth() / google.getWidth());
 }
  public void onTentativeMove(GeometryEditTentativeMoveEvent event) {
    try {
      Coordinate[] vertices =
          editingService
              .getIndexService()
              .getSiblingVertices(editingService.getGeometry(), editingService.getInsertIndex());
      String geometryType =
          editingService
              .getIndexService()
              .getGeometryType(editingService.getGeometry(), editingService.getInsertIndex());

      if (vertices != null && Geometry.LINE_STRING.equals(geometryType)) {
        String identifier =
            baseName
                + "."
                + editingService.getIndexService().format(editingService.getInsertIndex());
        Object parentGroup =
            groups.get(identifier.substring(0, identifier.lastIndexOf('.')) + ".edges");

        Coordinate temp1 = event.getOrigin();
        Coordinate temp2 = event.getCurrentPosition();
        Coordinate c1 =
            mapWidget.getMapModel().getMapView().getWorldViewTransformer().worldToPan(temp1);
        Coordinate c2 =
            mapWidget.getMapModel().getMapView().getWorldViewTransformer().worldToPan(temp2);

        LineString edge =
            mapWidget
                .getMapModel()
                .getGeometryFactory()
                .createLineString(new Coordinate[] {c1, c2});
        mapWidget
            .getVectorContext()
            .drawLine(
                parentGroup, insertMoveEdgeId1, edge, styleService.getEdgeTentativeMoveStyle());
      } else if (vertices != null && Geometry.LINEAR_RING.equals(geometryType)) {
        String identifier =
            baseName
                + "."
                + editingService.getIndexService().format(editingService.getInsertIndex());
        Object parentGroup =
            groups.get(identifier.substring(0, identifier.lastIndexOf('.')) + ".edges");

        // Line 1
        Coordinate temp1 = event.getOrigin();
        Coordinate temp2 = event.getCurrentPosition();
        Coordinate c1 =
            mapWidget.getMapModel().getMapView().getWorldViewTransformer().worldToPan(temp1);
        Coordinate c2 =
            mapWidget.getMapModel().getMapView().getWorldViewTransformer().worldToPan(temp2);
        LineString edge =
            mapWidget
                .getMapModel()
                .getGeometryFactory()
                .createLineString(new Coordinate[] {c1, c2});
        mapWidget
            .getVectorContext()
            .drawLine(
                parentGroup, insertMoveEdgeId1, edge, styleService.getEdgeTentativeMoveStyle());

        // Line 2
        if (styleService.isCloseRingWhileInserting()) {
          temp1 = vertices[vertices.length - 1];
          c1 = mapWidget.getMapModel().getMapView().getWorldViewTransformer().worldToPan(temp1);
          edge =
              mapWidget
                  .getMapModel()
                  .getGeometryFactory()
                  .createLineString(new Coordinate[] {c1, c2});
          mapWidget
              .getVectorContext()
              .drawLine(
                  parentGroup, insertMoveEdgeId2, edge, styleService.getEdgeTentativeMoveStyle());
        }
      }
    } catch (GeometryIndexNotFoundException e) {
      throw new IllegalStateException(e);
    }
  }
 public void redraw() {
   groups.clear();
   mapWidget.getVectorContext().deleteGroup(editingService.getGeometry());
   draw(editingService.getGeometry());
 }