public synchronized void initIndexes() {
   if (vertexIndex != null) {
     return;
   }
   graphService.setLoadLevel(LoadLevel.DEBUG);
   Graph graph = graphService.getGraph();
   vertexIndex = new STRtree();
   edgeIndex = new STRtree();
   for (Vertex v : graph.getVertices()) {
     Envelope vertexEnvelope = new Envelope(v.getCoordinate());
     vertexIndex.insert(vertexEnvelope, v);
     for (Edge e : v.getOutgoing()) {
       Envelope envelope;
       Geometry geometry = e.getGeometry();
       if (geometry == null) {
         envelope = vertexEnvelope;
       } else {
         envelope = geometry.getEnvelopeInternal();
       }
       edgeIndex.insert(envelope, e);
     }
   }
   vertexIndex.build();
   edgeIndex.build();
 }
 @SuppressWarnings("unchecked")
 private synchronized void findVisibleElements() {
   visibleVertices = (List<Vertex>) vertexIndex.query(modelBounds);
   visibleStreetEdges.clear();
   visibleTransitEdges.clear();
   for (Edge de : (Iterable<Edge>) edgeIndex.query(modelBounds)) {
     if (de instanceof PatternEdge || de instanceof StreetTransitLink) {
       visibleTransitEdges.add(de);
     } else if (de instanceof StreetEdge) {
       visibleStreetEdges.add(de);
     }
   }
 }
  /**
   * Get edges inside a bbox.
   *
   * @return
   */
  @Secured({"ROLE_USER"})
  @GET
  @Path("/edges")
  @Produces({MediaType.APPLICATION_JSON})
  public Object getEdges(
      @QueryParam("lowerLeft") String lowerLeft,
      @QueryParam("upperRight") String upperRight,
      @QueryParam("exactClass") String className,
      @QueryParam("skipTransit") boolean skipTransit,
      @QueryParam("skipStreets") boolean skipStreets,
      @QueryParam("skipNoGeometry") boolean skipNoGeometry) {

    initIndexes();

    Envelope envelope = getEnvelope(lowerLeft, upperRight);

    EdgeSet out = new EdgeSet();
    Graph graph = graphService.getGraph();

    @SuppressWarnings("unchecked")
    List<Edge> query = edgeIndex.query(envelope);
    out.edges = new ArrayList<WrappedEdge>();
    for (Edge e : query) {
      if (skipStreets && (e instanceof StreetEdge)) continue;
      if (skipTransit && !(e instanceof StreetEdge)) continue;
      if (skipNoGeometry && e.getGeometry() == null) continue;
      if (className != null && !e.getClass().getName().endsWith("." + className)) continue;
      out.edges.add(new WrappedEdge(e, graph.getIdForEdge(e)));
    }
    return out.withGraph(graph);
  }
Beispiel #4
0
 /**
  * areaTree全国区域拓扑树初始化
  *
  * @param fileName
  * @throws Exception void
  */
 public static void buildTree(String fileName) throws Exception {
   FileInputStream fis = new FileInputStream(new File(fileName));
   BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
   String line = null;
   AreaNode node = null;
   while ((line = br.readLine()) != null) { // 读取区域文件
     String[] lines = line.split(";");
     Geometry polygon = new WKTReader().read(lines[lines.length - 1]);
     node = new AreaNode(); // 创建节点
     node.setAreaCode(Long.parseLong(lines[0]));
     node.setAreaName(lines[1]);
     node.setPolygon(polygon);
     areaTree.insert(polygon.getEnvelopeInternal(), node); // 向树上添加节点
   }
   fis.close();
   br.close();
   areaTree.build(); // 构建树
 }
 public static ArrayList<String> getListOfSensors(String envelope) throws ParseException {
   Geometry geom = new WKTReader().read(envelope);
   List listEnvelope = geoIndex.query(geom.getEnvelopeInternal());
   ArrayList<String> sensors = new ArrayList<String>();
   for (int i = 0; i < listEnvelope.size(); i++) {
     sensors.add(searchForSensors_String((Point) listEnvelope.get(i)));
   }
   return sensors;
 }
 /*
  * Iterate through all vertices and their (outgoing) edges. If they are of 'interesting' types, add them to the corresponding spatial index.
  */
 public synchronized void buildSpatialIndex() {
   vertexIndex = new STRtree();
   edgeIndex = new STRtree();
   Envelope env;
   // int xminx, xmax, ymin, ymax;
   for (Vertex v : graph.getVertices()) {
     Coordinate c = v.getCoordinate();
     env = new Envelope(c);
     vertexIndex.insert(env, v);
     for (Edge e : v.getOutgoing()) {
       if (e.getGeometry() == null) continue;
       if (e instanceof PatternEdge || e instanceof StreetTransitLink || e instanceof StreetEdge) {
         env = e.getGeometry().getEnvelopeInternal();
         edgeIndex.insert(env, e);
       }
     }
   }
   vertexIndex.build();
   edgeIndex.build();
 }
  /*
   * Builds geographic geoIndex from list of sensors currently loaded in the system
   * */
  public static void buildGeoIndex() {

    geoIndex = new STRtree();
    geometryFactory = new GeometryFactory();
    sensors = new Vector<String>();
    coordinates = new Vector<Point>();

    getListOfSensors();

    for (int i = 0; i < sensors.size(); i++) {
      geoIndex.insert(coordinates.get(i).getEnvelopeInternal(), coordinates.get(i));
      logger.warn(
          sensors.get(i)
              + " : "
              + coordinates.get(i)
              + " : "
              + searchForSensors_String(coordinates.get(i)));
    }
    geoIndex.build();
  }
  public boolean onToolTouchEvent(MotionEvent event) {
    if (mapView == null || mapView.isClickable()) {
      return false;
    }

    Projection pj = mapView.getProjection();
    // handle drawing
    float currentX = event.getX();
    float currentY = event.getY();
    int deltaPixels = 100;

    int action = event.getAction();
    switch (action) {
      case MotionEvent.ACTION_DOWN:
      case MotionEvent.ACTION_MOVE:
        GeoPoint currentGeoPoint = pj.fromPixels(round(currentX), round(currentY));
        GeoPoint plusPoint =
            pj.fromPixels(round(currentX + deltaPixels), round(currentY + deltaPixels));

        double touchLon = currentGeoPoint.getLongitude();
        double touchLat = currentGeoPoint.getLatitude();
        double lonPlus = plusPoint.getLongitude();
        double latPlus = plusPoint.getLatitude();
        double deltaX = Math.abs(touchLon - lonPlus);
        double deltaY = Math.abs(touchLat - latPlus);
        Coordinate touchCoord = new Coordinate(touchLon, touchLat);
        Envelope queryEnvelope = new Envelope(touchCoord);
        queryEnvelope.expandBy(deltaX, deltaY);

        List<GpsLogInfo> result = gpsLogInfoTree.query(queryEnvelope);
        if (result.size() == 0) {
          return true;
        } else {
          GpsLogInfo nearest = null;
          double minDist = Double.POSITIVE_INFINITY;
          for (GpsLogInfo info : result) {
            double dist = touchCoord.distance(info.pointXYZ);
            if (dist < minDist) {
              minDist = dist;
              nearest = info;
            }
          }
          gpsLogInfo = nearest;
        }
        break;
      case MotionEvent.ACTION_UP:
        gpsLogInfo = null;
        break;
    }
    EditManager.INSTANCE.invalidateEditingView();
    return true;
  }
Beispiel #9
0
 /**
  * 根据经度、纬度获取区域编码
  *
  * @param lon 经度
  * @param lat 纬度
  * @return
  * @throws Exception long
  */
 public static long getAreaAnalyzer(double lon, double lat) throws Exception {
   long areacode = -1;
   Geometry geo = new GeometryFactory().createPoint(new Coordinate(lon, lat));
   List<?> areas = areaTree.query(geo.getEnvelopeInternal());
   for (Object obj : areas) {
     AreaNode anode = (AreaNode) obj;
     if (anode.getPolygon().contains(geo)) {
       areacode = anode.getAreaCode();
       break;
     }
   }
   return areacode;
 }
  @SuppressWarnings("unchecked")
  public Map<NBStop, List<Stop>> getPotentialStopMatches(
      List<NBRoute> nbRoutes, Collection<Stop> gtfsStops) {

    Map<String, NBStop> nbStopsByTag = getStopsByTag(nbRoutes);

    STRtree tree = new STRtree(gtfsStops.size());
    for (Stop stop : gtfsStops) {
      tree.insert(new Envelope(new Coordinate(stop.getLon(), stop.getLat())), stop);
    }
    tree.build();

    Map<NBStop, List<Stop>> potentialMatches = new HashMap<NBStop, List<Stop>>();
    int stopsWithNoMatches = 0;
    for (NBStop nbStop : nbStopsByTag.values()) {
      CoordinateBounds b =
          SphericalGeometryLibrary.bounds(
              nbStop.getLat(), nbStop.getLon(), _stopMatchingDistanceThreshold);
      Envelope env = new Envelope(b.getMinLon(), b.getMaxLon(), b.getMinLat(), b.getMaxLat());
      List<Stop> stopsInEnvelope = tree.query(env);
      if (stopsInEnvelope.isEmpty()) {
        _log.warn(
            "stop with no match: tag="
                + nbStop.getTag()
                + " lat="
                + nbStop.getLat()
                + " lon="
                + nbStop.getLon());
        stopsWithNoMatches++;
      }
      potentialMatches.put(nbStop, stopsInEnvelope);
    }

    if (stopsWithNoMatches > 0) {
      _log.warn("stops without matches: " + stopsWithNoMatches + "/" + nbStopsByTag.size());
    }

    return potentialMatches;
  }
  /**
   * Count vertices and edges inside a bbox.
   *
   * @return
   */
  @Secured({"ROLE_USER"})
  @GET
  @Path("/countFeatures")
  @Produces({MediaType.APPLICATION_JSON})
  public FeatureCount countVertices(
      @QueryParam("lowerLeft") String lowerLeft, @QueryParam("upperRight") String upperRight) {

    initIndexes();

    Envelope envelope = getEnvelope(lowerLeft, upperRight);

    FeatureCount out = new FeatureCount();

    @SuppressWarnings("unchecked")
    List<Vertex> vertexQuery = vertexIndex.query(envelope);
    out.vertices = vertexQuery.size();

    @SuppressWarnings("unchecked")
    List<Edge> edgeQuery = edgeIndex.query(envelope);
    out.edges = edgeQuery.size();

    return out;
  }
  /*
   * Setup Processing applet
   */
  public void setup() {
    size(getSize().width, getSize().height, P2D);

    /* Build spatial index of vertices and edges */
    buildSpatialIndex();

    /* Set model bounds to encompass all vertices in the index, and then some */
    modelBounds = (Envelope) (vertexIndex.getRoot().getBounds());
    modelBounds.expandBy(0.02);
    matchAspect();
    /* save this zoom level to allow returning to default later */
    modelOuterBounds = new Envelope(modelBounds);

    /* find and set up the appropriate font */
    String[] fonts = PFont.list();
    String[] preferredFonts = {"Mono", "Courier"};
    PFont font = null;
    for (String preferredFontName : preferredFonts) {
      for (String fontName : fonts) {
        if (fontName.contains(preferredFontName)) {
          font = createFont(fontName, 16);
          break;
        }
      }
      if (font != null) {
        break;
      }
    }
    textFont(font);
    textMode(SCREEN);
    addMouseWheelListener(this);
    addMouseMotionListener(
        new MouseMotionAdapter() {
          @Override
          public void mouseMoved(MouseEvent e) {
            super.mouseMoved(e);
            Point p = e.getPoint();
            mouseModelX = toModelX(p.x);
            mouseModelY = toModelY(p.y);
          }
        });
    addComponentListener(
        new ComponentAdapter() {
          public void componentResized(ComponentEvent e) {
            matchAspect();
            drawLevel = DRAW_PARTIAL;
          }
        });
    frameRate(FRAME_RATE);
  }
  @SuppressWarnings("unchecked")
  public void mouseClicked() {
    Envelope screenEnv = new Envelope(new Coordinate(mouseX, mouseY));
    screenEnv.expandBy(4, 4);
    Envelope env =
        new Envelope(
            toModelX(screenEnv.getMinX()),
            toModelX(screenEnv.getMaxX()),
            toModelY(screenEnv.getMinY()),
            toModelY(screenEnv.getMaxY()));

    List<Vertex> nearby = (List<Vertex>) vertexIndex.query(env);
    selector.verticesSelected(nearby);
    drawLevel = DRAW_ALL;
  }
  /**
   * Get vertices inside a bbox.
   *
   * @return
   */
  @Secured({"ROLE_USER"})
  @GET
  @Path("/vertices")
  @Produces({MediaType.APPLICATION_JSON})
  public Object getVertices(
      @QueryParam("lowerLeft") String lowerLeft,
      @QueryParam("upperRight") String upperRight,
      @QueryParam("pointsOnly") boolean pointsOnly,
      @QueryParam("exactClass") String className,
      @QueryParam("skipTransit") boolean skipTransit,
      @QueryParam("skipStreets") boolean skipStreets) {

    initIndexes();

    Envelope envelope = getEnvelope(lowerLeft, upperRight);

    @SuppressWarnings("unchecked")
    List<Vertex> query = vertexIndex.query(envelope);
    List<Vertex> filtered = new ArrayList<Vertex>();
    for (Vertex v : query) {
      if (skipTransit && v instanceof TransitVertex) continue;
      if (skipStreets && v instanceof StreetVertex) continue;
      if (className != null && !v.getClass().getName().endsWith("." + className)) continue;
      filtered.add(v);
    }
    if (pointsOnly) {
      SimpleVertexSet out = new SimpleVertexSet();
      out.vertices = new ArrayList<SimpleVertex>(filtered.size());
      for (Vertex v : filtered) {
        out.vertices.add(new SimpleVertex(v));
      }
      return out;
    } else {
      VertexSet out = new VertexSet();
      out.vertices = filtered;

      Graph graph = graphService.getGraph();
      return out.withGraph(graph);
    }
  }