示例#1
0
 ////////////////////////////////////////////// Working with amenities
 // ////////////////////////////////////////////////
 public List<Amenity> searchAmenities(
     SearchPoiTypeFilter filter,
     double topLatitude,
     double leftLongitude,
     double bottomLatitude,
     double rightLongitude,
     int zoom,
     final ResultMatcher<Amenity> matcher) {
   final List<Amenity> amenities = new ArrayList<Amenity>();
   searchAmenitiesInProgress = true;
   try {
     if (!filter.isEmpty()) {
       for (AmenityIndexRepository index : amenityRepositories.values()) {
         if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) {
           List<Amenity> r =
               index.searchAmenities(
                   MapUtils.get31TileNumberY(topLatitude),
                   MapUtils.get31TileNumberX(leftLongitude),
                   MapUtils.get31TileNumberY(bottomLatitude),
                   MapUtils.get31TileNumberX(rightLongitude),
                   zoom,
                   filter,
                   matcher);
           if (r != null) {
             amenities.addAll(r);
           }
         }
       }
     }
   } finally {
     searchAmenitiesInProgress = false;
   }
   return amenities;
 }
  @Override
  public void onListItemClick(ListView parent, View v, int position, long id) {
    final RouteInfoLocation item = ((TransportStopAdapter) getListAdapter()).getItem(position);
    Builder builder = new AlertDialog.Builder(this);
    List<String> items = new ArrayList<String>();
    final List<TransportStop> stops =
        item.getDirection()
            ? item.getRoute().getForwardStops()
            : item.getRoute().getBackwardStops();
    LatLon locationToGo = getLocationToGo();
    LatLon locationToStart = getLocationToStart();
    builder.setTitle(
        getString(R.string.transport_stop_to_go_out)
            + "\n"
            + getInformation(item, stops, getCurrentRouteLocation(), true)); // $NON-NLS-1$
    int ind = 0;
    for (TransportStop st : stops) {
      StringBuilder n = new StringBuilder(50);
      n.append(ind++);
      if (st == item.getStop()) {
        n.append("!! "); // $NON-NLS-1$
      } else {
        n.append(". "); // $NON-NLS-1$
      }
      String name = st.getName(settings.usingEnglishNames());
      if (locationToGo != null) {
        n.append(name).append(" - ["); // $NON-NLS-1$
        n.append(
                OsmAndFormatter.getFormattedDistance(
                    (int) MapUtils.getDistance(locationToGo, st.getLocation()),
                    (ClientContext) getApplication()))
            .append("]"); // $NON-NLS-1$
      } else if (locationToStart != null) {
        n.append("[")
            .append(
                OsmAndFormatter.getFormattedDistance(
                    (int) MapUtils.getDistance(locationToStart, st.getLocation()),
                    (ClientContext) getApplication()))
            .append("] - "); // $NON-NLS-1$ //$NON-NLS-2$
        n.append(name);
      } else {
        n.append(name);
      }
      items.add(n.toString());
    }
    builder.setItems(
        items.toArray(new String[items.size()]),
        new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialog, int which) {
            int i = which;
            if (i >= 0) {
              TransportStop stop = stops.get(i);
              showContextMenuOnStop(stop, item, i);
            }
          }
        });
    builder.show();
  }
示例#3
0
 protected void updateDistanceForBorderPoints(int sX, int sy, boolean distanceToStart) {
   boolean plus = borderLines.length > 0 && sy < borderLines[0].borderLine;
   if (borderLines.length > 0 && !plus && sy < borderLines[borderLines.length - 1].borderLine) {
     throw new IllegalStateException();
   }
   // calculate min distance to start
   for (int i = 0; i < borderLines.length; i++) {
     int ind = plus ? i : borderLines.length - i - 1;
     for (RouteDataBorderLinePoint ps : borderLines[ind].borderPoints) {
       float res = (float) Math.sqrt(MapUtils.squareDist31TileMetric(sX, sy, ps.x, ps.y));
       if (i > 0) {
         int prevInd = plus ? i - 1 : borderLines.length - i;
         double minDist = 0;
         for (RouteDataBorderLinePoint prevs : borderLines[prevInd].borderPoints) {
           double d =
               Math.sqrt(MapUtils.squareDist31TileMetric(prevs.x, prevs.y, ps.x, ps.y))
                   + (distanceToStart ? prevs.distanceToStartPoint : prevs.distanceToEndPoint);
           if (minDist == 0 || d < minDist) {
             minDist = d;
           }
         }
         if (minDist > 0) {
           //						System.out.println("Border line " + i + " exp="+res + " min="+ minDist);
           res = (float) minDist;
         }
       }
       if (distanceToStart) {
         ps.distanceToStartPoint = res;
       } else {
         ps.distanceToEndPoint = res;
       }
     }
   }
 }
示例#4
0
 public void updateUI(double latitude, double longitude) {
   latitude = MapUtils.checkLatitude(latitude);
   longitude = MapUtils.checkLongitude(longitude);
   final TextView latEdit = ((TextView) view.findViewById(R.id.LatitudeEdit));
   final TextView lonEdit = ((TextView) view.findViewById(R.id.LongitudeEdit));
   latEdit.setText(convert(latitude, currentFormat));
   lonEdit.setText(convert(longitude, currentFormat));
 }
  public String getInformation(
      RouteInfoLocation route, List<TransportStop> stops, int position, boolean part) {
    StringBuilder text = new StringBuilder(200);
    double dist = 0;
    int ind = 0;
    int stInd = stops.size();
    int eInd = stops.size();
    for (TransportStop s : stops) {
      if (s == route.getStart()) {
        stInd = ind;
      }
      if (s == route.getStop()) {
        eInd = ind;
      }
      if (ind > stInd && ind <= eInd) {
        dist += MapUtils.getDistance(stops.get(ind - 1).getLocation(), s.getLocation());
      }
      ind++;
    }
    text.append(getString(R.string.transport_route_distance))
        .append(" ")
        .append(
            OsmAndFormatter.getFormattedDistance(
                (int) dist, (ClientContext) getApplication())); // $NON-NLS-1$/
    if (!part) {
      text.append(", ")
          .append(getString(R.string.transport_stops_to_pass))
          .append(" ")
          .append(eInd - stInd); // $NON-NLS-1$ //$NON-NLS-2$
      LatLon endStop = getEndStop(position - 1);
      if (endStop != null) {
        String before =
            OsmAndFormatter.getFormattedDistance(
                (int) MapUtils.getDistance(endStop, route.getStart().getLocation()),
                (ClientContext) getApplication());
        text.append(", ")
            .append(getString(R.string.transport_to_go_before))
            .append(" ")
            .append(before); // $NON-NLS-2$//$NON-NLS-1$
      }

      LatLon stStop = getStartStop(position + 1);
      if (stStop != null) {
        String after =
            OsmAndFormatter.getFormattedDistance(
                (int) MapUtils.getDistance(stStop, route.getStop().getLocation()),
                (ClientContext) getApplication());
        text.append(", ")
            .append(getString(R.string.transport_to_go_after))
            .append(" ")
            .append(after); // $NON-NLS-1$ //$NON-NLS-2$
      }
    }

    return text.toString();
  }
示例#6
0
 @Override
 public int compare(GeocodingResult o1, GeocodingResult o2) {
   LatLon l1 = o1.getLocation();
   LatLon l2 = o2.getLocation();
   if (l1 == null || l2 == null) {
     return l2 == l1 ? 0 : (l1 == null ? -1 : 1);
   }
   return Double.compare(
       MapUtils.getDistance(l1, o1.searchPoint), MapUtils.getDistance(l2, o2.searchPoint));
 }
示例#7
0
 public List<GeocodingResult> reverseGeocodingSearch(RoutingContext ctx, double lat, double lon)
     throws IOException {
   RoutePlannerFrontEnd rp = new RoutePlannerFrontEnd(false);
   List<GeocodingResult> lst = new ArrayList<GeocodingUtilities.GeocodingResult>();
   List<RouteSegmentPoint> listR = new ArrayList<BinaryRoutePlanner.RouteSegmentPoint>();
   rp.findRouteSegment(lat, lon, ctx, listR);
   double distSquare = 0;
   TLongHashSet set = new TLongHashSet();
   Set<String> streetNames = new HashSet<String>();
   for (RouteSegmentPoint p : listR) {
     RouteDataObject road = p.getRoad();
     if (!set.add(road.getId())) {
       continue;
     }
     //			System.out.println(road.toString() +  " " + Math.sqrt(p.distSquare));
     boolean emptyName =
         Algorithms.isEmpty(road.getName()) && Algorithms.isEmpty(road.getRef("", false, true));
     if (!emptyName) {
       if (distSquare == 0 || distSquare > p.distSquare) {
         distSquare = p.distSquare;
       }
       GeocodingResult sr = new GeocodingResult();
       sr.searchPoint = new LatLon(lat, lon);
       sr.streetName =
           Algorithms.isEmpty(road.getName()) ? road.getRef("", false, true) : road.getName();
       sr.point = p;
       sr.connectionPoint =
           new LatLon(MapUtils.get31LatitudeY(p.preciseY), MapUtils.get31LongitudeX(p.preciseX));
       sr.regionFP = road.region.getFilePointer();
       sr.regionLen = road.region.getLength();
       if (streetNames.add(sr.streetName)) {
         lst.add(sr);
       }
     }
     if (p.distSquare
             > STOP_SEARCHING_STREET_WITH_MULTIPLIER_RADIUS
                 * STOP_SEARCHING_STREET_WITH_MULTIPLIER_RADIUS
         && distSquare != 0
         && p.distSquare > THRESHOLD_MULTIPLIER_SKIP_STREETS_AFTER * distSquare) {
       break;
     }
     if (p.distSquare
         > STOP_SEARCHING_STREET_WITHOUT_MULTIPLIER_RADIUS
             * STOP_SEARCHING_STREET_WITHOUT_MULTIPLIER_RADIUS) {
       break;
     }
   }
   Collections.sort(lst, GeocodingUtilities.DISTANCE_COMPARATOR);
   return lst;
 }
示例#8
0
  public List<Amenity> searchAmenitiesByName(
      String searchQuery,
      double topLatitude,
      double leftLongitude,
      double bottomLatitude,
      double rightLongitude,
      double lat,
      double lon,
      ResultMatcher<Amenity> matcher) {
    List<Amenity> amenities = new ArrayList<Amenity>();
    List<AmenityIndexRepositoryBinary> list = new ArrayList<AmenityIndexRepositoryBinary>();
    for (AmenityIndexRepository index : amenityRepositories.values()) {
      if (index instanceof AmenityIndexRepositoryBinary) {
        if (index.checkContains(topLatitude, leftLongitude, bottomLatitude, rightLongitude)) {
          if (index.checkContains(lat, lon)) {
            list.add(0, (AmenityIndexRepositoryBinary) index);
          } else {
            list.add((AmenityIndexRepositoryBinary) index);
          }
        }
      }
    }
    //		int left = MapUtils.get31TileNumberX(leftLongitude);
    //		int top = MapUtils.get31TileNumberY(topLatitude);
    //		int right = MapUtils.get31TileNumberX(rightLongitude);
    //		int bottom = MapUtils.get31TileNumberY(bottomLatitude);
    int left = 0;
    int top = 0;
    int right = Integer.MAX_VALUE;
    int bottom = Integer.MAX_VALUE;
    for (AmenityIndexRepositoryBinary index : list) {
      if (matcher != null && matcher.isCancelled()) {
        break;
      }
      List<Amenity> result =
          index.searchAmenitiesByName(
              MapUtils.get31TileNumberX(lon),
              MapUtils.get31TileNumberY(lat),
              left,
              top,
              right,
              bottom,
              searchQuery,
              matcher);
      amenities.addAll(result);
    }

    return amenities;
  }
 public double getTopLatitude() {
   double l = -90;
   for (RouteSubregion s : subregions) {
     l = Math.max(l, MapUtils.get31LatitudeY(s.top));
   }
   return l;
 }
 public double getBottomLatitude() {
   double l = 90;
   for (RouteSubregion s : subregions) {
     l = Math.min(l, MapUtils.get31LatitudeY(s.bottom));
   }
   return l;
 }
 public double getRightLongitude() {
   double l = -180;
   for (RouteSubregion s : subregions) {
     l = Math.max(l, MapUtils.get31LongitudeX(s.right));
   }
   return l;
 }
 public double getLeftLongitude() {
   double l = 180;
   for (RouteSubregion s : subregions) {
     l = Math.min(l, MapUtils.get31LongitudeX(s.left));
   }
   return l;
 }
示例#13
0
 @Override
 public void onZoomEnded(double relativeToStart, float angleRelative) {
   // 1.5 works better even on dm.density=1 devices
   float dz = (float) (Math.log(relativeToStart) / Math.log(2)) * 1.5f;
   setIntZoom(Math.round(dz) + initialViewport.getZoom());
   if (Math.abs(angleRelative) < ANGLE_THRESHOLD) {
     angleRelative = 0;
   }
   rotateToAnimate(initialViewport.getRotate() + angleRelative);
   final int newZoom = getZoom();
   if (application.getInternalAPI().accessibilityEnabled()) {
     if (newZoom != initialViewport.getZoom()) {
       showMessage(getContext().getString(R.string.zoomIs) + " " + newZoom); // $NON-NLS-1$
     } else {
       final LatLon p1 = initialViewport.getLatLonFromPixel(x1, y1);
       final LatLon p2 = initialViewport.getLatLonFromPixel(x2, y2);
       showMessage(
           OsmAndFormatter.getFormattedDistance(
               (float)
                   MapUtils.getDistance(
                       p1.getLatitude(), p1.getLongitude(), p2.getLatitude(), p2.getLongitude()),
               application));
     }
   }
 }
示例#14
0
 protected void rotateToAnimate(float rotate) {
   if (isMapRotateEnabled()) {
     this.rotate = MapUtils.unifyRotationTo360(rotate);
     currentViewport.setRotate(this.rotate);
     refreshMap();
   }
 }
示例#15
0
 public boolean identifyUTurnIsNeeded(Location currentLocation, float posTolerance) {
   if (finalLocation == null || currentLocation == null || !route.isCalculated()) {
     this.makeUturnWhenPossible = false;
     return makeUturnWhenPossible;
   }
   boolean makeUturnWhenPossible = false;
   if (currentLocation.hasBearing()) {
     float bearingMotion = currentLocation.getBearing();
     Location nextRoutePosition = route.getNextRouteLocation();
     float bearingToRoute = currentLocation.bearingTo(nextRoutePosition);
     double diff = MapUtils.degreesDiff(bearingMotion, bearingToRoute);
     // 7. Check if you left the route and an unscheduled U-turn would bring you back (also Issue
     // 863)
     // This prompt is an interim advice and does only sound if a new route in forward direction
     // could not be found in x seconds
     if (Math.abs(diff) > 135f) {
       float d = currentLocation.distanceTo(nextRoutePosition);
       // 60m tolerance to allow for GPS inaccuracy
       if (d > posTolerance) {
         // require x sec continuous since first detection
         if (makeUTwpDetected == 0) {
           makeUTwpDetected = System.currentTimeMillis();
         } else if ((System.currentTimeMillis() - makeUTwpDetected > 10000)) {
           makeUturnWhenPossible = true;
           // log.info("bearingMotion is opposite to bearingRoute"); //$NON-NLS-1$
         }
       }
     } else {
       makeUTwpDetected = 0;
     }
   }
   this.makeUturnWhenPossible = makeUturnWhenPossible;
   return makeUturnWhenPossible;
 }
示例#16
0
 public void setRotate(float rotate) {
   if (isMapRotateEnabled()) {
     float diff = MapUtils.unifyRotationDiff(rotate, getRotate());
     if (Math.abs(diff) > 5) { // check smallest rotation
       animatedDraggingThread.startRotate(rotate);
     }
   }
 }
示例#17
0
 private static double getOrthogonalDistance(Location loc, Location from, Location to) {
   return MapUtils.getOrthogonalDistance(
       loc.getLatitude(),
       loc.getLongitude(),
       from.getLatitude(),
       from.getLongitude(),
       to.getLatitude(),
       to.getLongitude());
 }
示例#18
0
 private static LatLon getProject(Location loc, Location from, Location to) {
   return MapUtils.getProjection(
       loc.getLatitude(),
       loc.getLongitude(),
       from.getLatitude(),
       from.getLongitude(),
       to.getLatitude(),
       to.getLongitude());
 }
示例#19
0
 private void updateLabel(
     final int zoom,
     final QuadRect latlonRect,
     final TextView downloadText,
     final String template,
     int progress) {
   int numberTiles = 0;
   for (int z = zoom; z <= progress + zoom; z++) {
     int x1 = (int) MapUtils.getTileNumberX(z, latlonRect.left);
     int x2 = (int) MapUtils.getTileNumberX(z, latlonRect.right);
     int y1 = (int) MapUtils.getTileNumberY(z, latlonRect.top);
     int y2 = (int) MapUtils.getTileNumberY(z, latlonRect.bottom);
     numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1);
   }
   downloadText.setText(
       MessageFormat.format(
           template,
           (progress + zoom) + "", // $NON-NLS-1$
           numberTiles,
           (double) numberTiles * 12 / 1000));
 }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      View row = convertView;
      if (row == null) {
        LayoutInflater inflater = getLayoutInflater();
        row = inflater.inflate(R.layout.search_transport_list_item, parent, false);
      }
      LatLon locationToGo = getLocationToGo();
      LatLon locationToStart = getLocationToStart();

      TextView label = (TextView) row.findViewById(R.id.label);
      ImageView icon = (ImageView) row.findViewById(R.id.search_icon);
      RouteInfoLocation stop = getItem(position);

      TransportRoute route = stop.getRoute();
      StringBuilder labelW = new StringBuilder(150);
      labelW.append(route.getType()).append(" ").append(route.getRef()); // $NON-NLS-1$
      labelW.append(" - ["); // $NON-NLS-1$

      if (locationToGo != null) {
        labelW.append(
            OsmAndFormatter.getFormattedDistance(
                stop.getDistToLocation(), (ClientContext) getApplication()));
      } else {
        labelW.append(getString(R.string.transport_search_none));
      }
      labelW.append("]\n").append(route.getName(settings.usingEnglishNames())); // $NON-NLS-1$

      // TODO icons
      if (locationToGo != null && stop.getDistToLocation() < 400) {
        icon.setImageResource(R.drawable.opened_poi);
      } else {
        icon.setImageResource(R.drawable.poi);
      }

      int dist =
          locationToStart == null
              ? 0
              : (int) (MapUtils.getDistance(stop.getStart().getLocation(), locationToStart));
      String distance =
          OsmAndFormatter.getFormattedDistance(dist, (ClientContext) getApplication())
              + " "; //$NON-NLS-1$
      label.setText(distance + labelW.toString(), TextView.BufferType.SPANNABLE);
      ((Spannable) label.getText())
          .setSpan(
              new ForegroundColorSpan(getResources().getColor(R.color.color_distance)),
              0,
              distance.length() - 1,
              0);
      return (row);
    }
示例#21
0
 public boolean onTouchEvent(MotionEvent event) {
   if (!isMultiTouchSupported()) {
     return false;
   }
   int actionCode = event.getAction() & ACTION_MASK;
   try {
     Integer pointCount = (Integer) getPointerCount.invoke(event);
     if (pointCount < 2) {
       if (inZoomMode) {
         listener.onZoomEnded(zoomRelative, angleRelative);
       }
       return false;
     }
     Float x1 = (Float) getX.invoke(event, 0);
     Float x2 = (Float) getX.invoke(event, 1);
     Float y1 = (Float) getY.invoke(event, 0);
     Float y2 = (Float) getY.invoke(event, 1);
     float distance = (float) Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
     float angle = 0;
     boolean angleDefined = false;
     if (x1 != x2 || y1 != y2) {
       angleDefined = true;
       angle = (float) (Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI);
     }
     if (actionCode == ACTION_POINTER_DOWN) {
       centerPoint = new PointF((x1 + x2) / 2, (y1 + y2) / 2);
       listener.onGestureInit(x1, y1, x2, y2);
       listener.onZoomStarted(centerPoint);
       zoomStartedDistance = distance;
       angleStarted = angle;
       inZoomMode = true;
       return true;
     } else if (actionCode == ACTION_POINTER_UP) {
       if (inZoomMode) {
         listener.onZoomEnded(zoomRelative, angleRelative);
         inZoomMode = false;
       }
       return true;
     } else if (inZoomMode && actionCode == MotionEvent.ACTION_MOVE) {
       if (angleDefined) {
         angleRelative = MapUtils.unifyRotationTo360(angle - angleStarted);
       }
       zoomRelative = distance / zoomStartedDistance;
       listener.onZoomingOrRotating(zoomRelative, angleRelative);
       return true;
     }
   } catch (Exception e) {
     log.debug("Multi touch exception", e); // $NON-NLS-1$
   }
   return false;
 }
示例#22
0
 private float dist(LocationPoint l, List<Location> locations, int[] ind) {
   float dist = Float.POSITIVE_INFINITY;
   // Special iterations because points stored by pairs!
   for (int i = 1; i < locations.size(); i++) {
     final double ld =
         MapUtils.getOrthogonalDistance(
             l.getLatitude(), l.getLongitude(),
             locations.get(i - 1).getLatitude(), locations.get(i - 1).getLongitude(),
             locations.get(i).getLatitude(), locations.get(i).getLongitude());
     if (ld < dist) {
       if (ind != null) {
         ind[0] = i;
       }
       dist = (float) ld;
     }
   }
   return dist;
 }
  @Override
  public Node loadNode(Amenity n) {
    if (n.getId() % 2 == 1) {
      // that's way id
      return null;
    }
    long nodeId = n.getId() >> 1;
    try {
      String res =
          sendRequest(
              SITE_API + "api/0.6/node/" + nodeId,
              "GET",
              null,
              ctx.getString(R.string.loading_poi_obj) + nodeId,
              false); //$NON-NLS-1$ //$NON-NLS-2$
      if (res != null) {
        OsmBaseStorage st = new OsmBaseStorage();
        st.parseOSM(
            new ByteArrayInputStream(res.getBytes("UTF-8")), null, null, true); // $NON-NLS-1$
        EntityId id = new Entity.EntityId(EntityType.NODE, nodeId);
        Node entity = (Node) st.getRegisteredEntities().get(id);
        entityInfo = st.getRegisteredEntityInfo().get(id);
        // check whether this is node (because id of node could be the same as relation)
        if (entity != null && MapUtils.getDistance(entity.getLatLon(), n.getLocation()) < 50) {
          return entity;
        }
        return null;
      }

    } catch (IOException e) {
      log.error("Loading node failed " + nodeId, e); // $NON-NLS-1$
      AccessibleToast.makeText(
              ctx, ctx.getResources().getString(R.string.error_io_error), Toast.LENGTH_LONG)
          .show();
    } catch (SAXException e) {
      log.error("Loading node failed " + nodeId, e); // $NON-NLS-1$
      AccessibleToast.makeText(
              ctx, ctx.getResources().getString(R.string.error_io_error), Toast.LENGTH_LONG)
          .show();
    }
    return null;
  }
示例#24
0
 public Polygon getPolygon(int tileX, int tileY, int z) {
   int pixX =
       (int)
           (MapUtils.getPixelShiftX(
                   map.getZoom(),
                   MapUtils.getLongitudeFromTile(z, tileX),
                   map.getLongitude(),
                   map.getTileSize())
               + map.getCenterPointX());
   int pixY =
       (int)
           (MapUtils.getPixelShiftY(
                   map.getZoom(),
                   MapUtils.getLatitudeFromTile(z, tileY),
                   map.getLatitude(),
                   map.getTileSize())
               + map.getCenterPointY());
   int pixsX =
       (int)
           (MapUtils.getPixelShiftX(
                   map.getZoom(),
                   MapUtils.getLongitudeFromTile(z, tileX + 1),
                   map.getLongitude(),
                   map.getTileSize())
               + map.getCenterPointX());
   int pixsY =
       (int)
           (MapUtils.getPixelShiftY(
                   map.getZoom(),
                   MapUtils.getLatitudeFromTile(z, tileY + 1),
                   map.getLatitude(),
                   map.getTileSize())
               + map.getCenterPointY());
   return new Polygon(
       new int[] {pixX, pixsX, pixsX, pixX, pixX}, new int[] {pixY, pixY, pixsY, pixsY, pixY}, 5);
 }
示例#25
0
 public AlarmInfo calculateMostImportantAlarm(
     RouteDataObject ro, Location loc, MetricsConstants mc, boolean showCameras) {
   boolean direction = true;
   if (loc.hasBearing()) {
     double diff =
         MapUtils.alignAngleDifference(
             ro.directionRoute(0, true) - loc.getBearing() / (2 * Math.PI));
     direction = Math.abs(diff) < Math.PI;
   }
   float mxspeed = ro.getMaximumSpeed(direction);
   float delta = app.getSettings().SPEED_LIMIT_EXCEED.get() / 3.6f;
   AlarmInfo speedAlarm = createSpeedAlarm(mc, mxspeed, loc, delta);
   if (speedAlarm != null) {
     getVoiceRouter().announceSpeedAlarm();
     return speedAlarm;
   }
   for (int i = 0; i < ro.getPointsLength(); i++) {
     int[] pointTypes = ro.getPointTypes(i);
     RouteRegion reg = ro.region;
     if (pointTypes != null) {
       for (int r = 0; r < pointTypes.length; r++) {
         RouteTypeRule typeRule = reg.quickGetEncodingRule(pointTypes[r]);
         AlarmInfo info = AlarmInfo.createAlarmInfo(typeRule, 0, loc);
         if (info != null) {
           if (info.getType() != AlarmInfoType.SPEED_CAMERA || showCameras) {
             long ms = System.currentTimeMillis();
             if (ms - announcedAlarmTime > 50 * 1000) {
               announcedAlarmTime = ms;
               getVoiceRouter().announceAlarm(info.getType());
             }
             return info;
           }
         }
       }
     }
   }
   return null;
 }
示例#26
0
 /**
  * Wrong movement direction is considered when between current location bearing (determines by 2
  * last fixed position or provided) and bearing from currentLocation to next (current) point the
  * difference is more than 60 degrees
  */
 public boolean checkWrongMovementDirection(Location currentLocation, Location nextRouteLocation) {
   // measuring without bearing could be really error prone (with last fixed location)
   // this code has an effect on route recalculation which should be detected without mistakes
   if (currentLocation.hasBearing() && nextRouteLocation != null) {
     float bearingMotion = currentLocation.getBearing();
     float bearingToRoute = currentLocation.bearingTo(nextRouteLocation);
     double diff = MapUtils.degreesDiff(bearingMotion, bearingToRoute);
     if (Math.abs(diff) > 60f) {
       // require delay interval since first detection, to avoid false positive
       // but leave out for now, as late detection is worse than false positive (it may reset voice
       // router then cause bogus turn and u-turn prompting)
       // if (wrongMovementDetected == 0) {
       //	wrongMovementDetected = System.currentTimeMillis();
       // } else if ((System.currentTimeMillis() - wrongMovementDetected > 500)) {
       return true;
       // }
     } else {
       // wrongMovementDetected = 0;
       return false;
     }
   }
   // wrongMovementDetected = 0;
   return false;
 }
示例#27
0
  public void run(
      final int zoom, final int progress, final QuadRect latlonRect, final ITileSource map) {
    cancel = false;
    int numberTiles = 0;
    for (int z = zoom; z <= progress + zoom; z++) {
      int x1 = (int) MapUtils.getTileNumberX(z, latlonRect.left);
      int x2 = (int) MapUtils.getTileNumberX(z, latlonRect.right);
      int y1 = (int) MapUtils.getTileNumberY(z, latlonRect.top);
      int y2 = (int) MapUtils.getTileNumberY(z, latlonRect.bottom);
      numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1);
    }
    final ProgressDialog progressDlg = new ProgressDialog(ctx);
    progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDlg.setMessage(
        ctx.getString(R.string.shared_string_downloading)
            + ctx.getString(R.string.shared_string_ellipsis));
    progressDlg.setCancelable(true);
    progressDlg.setMax(numberTiles);
    progressDlg.setOnCancelListener(
        new DialogInterface.OnCancelListener() {

          @Override
          public void onCancel(DialogInterface dialog) {
            cancel = true;
          }
        });

    final MapTileDownloader instance = MapTileDownloader.getInstance(Version.getFullVersion(app));

    final List<IMapDownloaderCallback> previousCallbacks = instance.getDownloaderCallbacks();
    instance.clearCallbacks();
    callback =
        new IMapDownloaderCallback() {
          @Override
          public void tileDownloaded(DownloadRequest request) {
            if (request != null) {
              progressDlg.setProgress(progressDlg.getProgress() + 1);
            }
          }
        };
    instance.addDownloaderCallback(callback);

    Runnable r =
        new Runnable() {
          @Override
          public void run() {
            int requests = 0;
            int limitRequests = 50;
            try {
              ResourceManager rm = app.getResourceManager();
              for (int z = zoom; z <= zoom + progress && !cancel; z++) {
                int x1 = (int) MapUtils.getTileNumberX(z, latlonRect.left);
                int x2 = (int) MapUtils.getTileNumberX(z, latlonRect.right);
                int y1 = (int) MapUtils.getTileNumberY(z, latlonRect.top);
                int y2 = (int) MapUtils.getTileNumberY(z, latlonRect.bottom);
                for (int x = x1; x <= x2 && !cancel; x++) {
                  for (int y = y1; y <= y2 && !cancel; y++) {
                    String tileId = rm.calculateTileId(map, x, y, z);
                    if (rm.tileExistOnFileSystem(tileId, map, x, y, z)) {
                      progressDlg.setProgress(progressDlg.getProgress() + 1);
                    } else {
                      rm.getTileImageForMapSync(tileId, map, x, y, z, true);
                      requests++;
                    }
                    if (!cancel) {
                      if (requests >= limitRequests) {
                        requests = 0;

                        while (instance.isSomethingBeingDownloaded()) {
                          try {
                            Thread.sleep(500);
                          } catch (InterruptedException e) {
                            throw new IllegalArgumentException(e);
                          }
                        }
                      }
                    }
                  }
                }
              }
              if (cancel) {
                instance.refuseAllPreviousRequests();
              } else {
                while (instance.isSomethingBeingDownloaded()) {
                  try {
                    Thread.sleep(500);
                  } catch (InterruptedException e) {
                    throw new IllegalArgumentException(e);
                  }
                }
              }
              mapView.refreshMap();
              callback = null;
            } catch (Exception e) {
              log.error("Exception while downloading tiles ", e); // $NON-NLS-1$
              instance.refuseAllPreviousRequests();
            } finally {
              instance.clearCallbacks();
              for (IMapDownloaderCallback cbck : previousCallbacks) {
                instance.addDownloaderCallback(cbck);
              }
              app.getResourceManager().reloadTilesFromFS();
            }
            progressDlg.dismiss();
          }
        };

    new Thread(r, "Downloading tiles").start(); // $NON-NLS-1$
    progressDlg.show();
  }
示例#28
0
  public void initUI(double latitude, double longitude) {
    latitude = MapUtils.checkLatitude(latitude);
    longitude = MapUtils.checkLongitude(longitude);
    final TextView latEdit = ((TextView) view.findViewById(R.id.LatitudeEdit));
    final TextView lonEdit = ((TextView) view.findViewById(R.id.LongitudeEdit));
    currentFormat = Location.FORMAT_DEGREES;
    latEdit.setText(convert(latitude, Location.FORMAT_DEGREES));
    lonEdit.setText(convert(longitude, Location.FORMAT_DEGREES));
    final Spinner format = ((Spinner) view.findViewById(R.id.Format));
    ArrayAdapter<String> adapter =
        new ArrayAdapter<String>(
            getSherlockActivity(),
            android.R.layout.simple_spinner_item,
            new String[] {
              getString(R.string.navigate_point_format_D),
              getString(R.string.navigate_point_format_DM),
              getString(R.string.navigate_point_format_DMS)
            });
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    format.setAdapter(adapter);
    format.setSelection(0);
    format.setOnItemSelectedListener(
        new OnItemSelectedListener() {

          @Override
          public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
            int newFormat = currentFormat;
            String itm = (String) format.getItemAtPosition(position);
            if (getString(R.string.navigate_point_format_D).equals(itm)) {
              newFormat = Location.FORMAT_DEGREES;
            } else if (getString(R.string.navigate_point_format_DM).equals(itm)) {
              newFormat = Location.FORMAT_MINUTES;
            } else if (getString(R.string.navigate_point_format_DMS).equals(itm)) {
              newFormat = Location.FORMAT_SECONDS;
            }
            currentFormat = newFormat;
            try {
              double lat =
                  convert(((TextView) view.findViewById(R.id.LatitudeEdit)).getText().toString());
              double lon =
                  convert(((TextView) view.findViewById(R.id.LongitudeEdit)).getText().toString());
              ((TextView) view.findViewById(R.id.ValidateTextView)).setVisibility(View.INVISIBLE);
              latEdit.setText(convert(lat, newFormat));
              lonEdit.setText(convert(lon, newFormat));
            } catch (RuntimeException e) {
              ((TextView) view.findViewById(R.id.ValidateTextView)).setVisibility(View.VISIBLE);
              ((TextView) view.findViewById(R.id.ValidateTextView))
                  .setText(R.string.invalid_locations);
              Log.w(PlatformUtil.TAG, "Convertion failed", e); // $NON-NLS-1$
            }
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {}
        });
    TextWatcher textWatcher =
        new TextWatcher() {
          String pasteString = null;

          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {
            pasteString = null;
            if (count > 3) {
              pasteString = s.subSequence(start, start + count).toString();
            }
          }

          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          @Override
          public void afterTextChanged(Editable s) {

            if (pasteString != null) {
              int latSt = -1;
              int latEnd = -1;
              int lonSt = -1;
              int lonEnd = -1;
              int step = 0; // 0 - init, 1- lat, 2-between, 3-lon
              for (int i = 0; i < pasteString.length(); i++) {
                char ch = pasteString.charAt(i);
                if (Character.isDigit(ch)) {
                  if (step == 0 || step == 2) {
                    int t = i;
                    if (i > 0 && pasteString.charAt(i - 1) == '-') {
                      t--;
                    }
                    if (step == 0) {
                      latSt = t;
                    } else {
                      lonSt = t;
                    }
                    step++;
                  }
                } else if (ch == '.' || ch == ':') {
                  // do nothing here
                } else {
                  if (step == 1) {
                    latEnd = i;
                    step++;
                  } else if (step == 3) {
                    lonEnd = i;
                    step++;
                    break;
                  }
                }
              }

              if (lonSt != -1) {
                if (lonEnd == -1) {
                  lonEnd = pasteString.length();
                }
                try {
                  String latString = pasteString.substring(latSt, latEnd);
                  String lonString = pasteString.substring(lonSt, lonEnd);
                  Double.parseDouble(latString);
                  Double.parseDouble(lonString);
                  latEdit.setText(latString);
                  lonEdit.setText(lonString);
                } catch (NumberFormatException e) {
                }
              }
            }
          }
        };
    latEdit.addTextChangedListener(textWatcher);
    lonEdit.addTextChangedListener(textWatcher);
  }
示例#29
0
 public String getDistance(RoutePoint rp) {
   double d = MapUtils.getDistance(rp.getPoint(), getPoint());
   String distance = OsmAndFormatter.getFormattedDistance((float) d, app);
   return distance;
 }
示例#30
0
 public void announceVisibleLocations() {
   Location lastKnownLocation = app.getRoutingHelper().getLastProjection();
   if (lastKnownLocation != null && app.getRoutingHelper().isFollowingMode()) {
     for (int type = 0; type < locationPoints.size(); type++) {
       int currentRoute = route.getCurrentRoute();
       List<LocationPointWrapper> approachPoints = new ArrayList<LocationPointWrapper>();
       List<LocationPointWrapper> announcePoints = new ArrayList<LocationPointWrapper>();
       List<LocationPointWrapper> lp = locationPoints.get(type);
       if (lp != null) {
         int kIterator = pointsProgress.get(type);
         while (kIterator < lp.size() && lp.get(kIterator).routeIndex < currentRoute) {
           kIterator++;
         }
         pointsProgress.set(type, kIterator);
         while (kIterator < lp.size()) {
           LocationPointWrapper lwp = lp.get(kIterator);
           if (route.getDistanceToPoint(lwp.routeIndex) > LONG_ANNOUNCE_RADIUS * 2) {
             break;
           }
           LocationPoint point = lwp.point;
           double d1 =
               Math.max(
                   0.0,
                   MapUtils.getDistance(
                           lastKnownLocation.getLatitude(),
                           lastKnownLocation.getLongitude(),
                           point.getLatitude(),
                           point.getLongitude())
                       - lwp.getDeviationDistance());
           Integer state = locationPointsStates.get(point);
           if (state != null
               && state.intValue() == ANNOUNCED_ONCE
               && getVoiceRouter()
                   .isDistanceLess(lastKnownLocation.getSpeed(), d1, SHORT_ANNOUNCE_RADIUS, 0f)) {
             locationPointsStates.put(point, ANNOUNCED_DONE);
             announcePoints.add(lwp);
           } else if (type != ALARMS
               && (state == null || state == NOT_ANNOUNCED)
               && getVoiceRouter()
                   .isDistanceLess(lastKnownLocation.getSpeed(), d1, LONG_ANNOUNCE_RADIUS, 0f)) {
             locationPointsStates.put(point, ANNOUNCED_ONCE);
             approachPoints.add(lwp);
           } else if (type == ALARMS
               && (state == null || state == NOT_ANNOUNCED)
               && getVoiceRouter()
                   .isDistanceLess(lastKnownLocation.getSpeed(), d1, ALARMS_ANNOUNCE_RADIUS, 0f)) {
             locationPointsStates.put(point, ANNOUNCED_ONCE);
             approachPoints.add(lwp);
           }
           kIterator++;
         }
         if (!announcePoints.isEmpty()) {
           if (announcePoints.size() > ANNOUNCE_POI_LIMIT) {
             announcePoints = announcePoints.subList(0, ANNOUNCE_POI_LIMIT);
           }
           if (type == WAYPOINTS) {
             getVoiceRouter().announceWaypoint(announcePoints);
           } else if (type == POI) {
             getVoiceRouter().announcePoi(announcePoints);
           } else if (type == ALARMS) {
             // nothing to announce
           } else if (type == FAVORITES) {
             getVoiceRouter().announceFavorite(announcePoints);
           }
         }
         if (!approachPoints.isEmpty()) {
           if (approachPoints.size() > APPROACH_POI_LIMIT) {
             approachPoints = approachPoints.subList(0, APPROACH_POI_LIMIT);
           }
           if (type == WAYPOINTS) {
             getVoiceRouter().approachWaypoint(lastKnownLocation, approachPoints);
           } else if (type == POI) {
             getVoiceRouter().approachPoi(lastKnownLocation, approachPoints);
           } else if (type == ALARMS) {
             EnumSet<AlarmInfoType> ait = EnumSet.noneOf(AlarmInfoType.class);
             for (LocationPointWrapper pw : approachPoints) {
               ait.add(((AlarmInfo) pw.point).getType());
             }
             for (AlarmInfoType t : ait) {
               app.getRoutingHelper().getVoiceRouter().announceAlarm(t);
             }
           } else if (type == FAVORITES) {
             getVoiceRouter().approachFavorite(lastKnownLocation, approachPoints);
           }
         }
       }
     }
   }
 }