@Override
  public void updateLocationMarker(Location location) {
    if (locationChangedListener != null) {
      currentUserLocation = location;
      locationChangedListener.onLocationChanged(location);
    }

    // Update clickable area
    LatLng userPosition = getUserLocation(location);
    if (userPositionClickArea == null) {
      MarkerOptions markerOptions = new MarkerOptions();
      markerOptions.position(userPosition);
      markerOptions.anchor(0.4f, 0.4f); // strange google maps bug
      markerOptions.icon(BitmapDescriptorFactory.fromBitmap(clickableBitmap));
      userPositionClickArea = googleMap.addMarker(markerOptions);
    } else {
      userPositionClickArea.setPosition(userPosition);
    }
    if (userPositionClickArea2 == null) {
      MarkerOptions markerOptions = new MarkerOptions();
      markerOptions.position(userPosition);
      markerOptions.anchor(0.6f, 0.6f); // strange google maps bug
      markerOptions.icon(BitmapDescriptorFactory.fromBitmap(clickableBitmap));
      userPositionClickArea2 = googleMap.addMarker(markerOptions);
    } else {
      userPositionClickArea2.setPosition(userPosition);
    }
  }
Пример #2
0
  public void addCreatures(Location location) {
    map.clear();
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    Toast.makeText(this, location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_SHORT)
        .show();
    double clat = latLng.latitude + 0.05;
    double clng = latLng.longitude + 0.05;
    Toast.makeText(this, clat + " " + clng, Toast.LENGTH_SHORT).show();
    double flat = latLng.latitude - 0.125;
    double flng = latLng.longitude - 0.125;
    Toast.makeText(this, flat + " " + flng, Toast.LENGTH_SHORT).show();
    int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    Random random_spawn = new Random(hour);
    for (int i = 0; i < 2000; i++) {
      double randomLat = (flat) + (random_spawn.nextDouble() * 0.25);
      double randomLng = (flng) + (random_spawn.nextDouble() * 0.25);
      CreatureGenerator creature = new CreatureGenerator(randomLat, randomLng);
      Bitmap b = creature.getBitmap(32);
      map.addMarker(
          new MarkerOptions()
              .position(new LatLng(randomLat, randomLng))
              .title(creature.getName())
              .icon(BitmapDescriptorFactory.fromBitmap(b)));
    }

    CreatureGenerator creature =
        new CreatureGenerator(location.getLatitude() - 0.0005, location.getLongitude() + 0.0005);
    Bitmap b = creature.getBitmap(32);
    map.addMarker(
        new MarkerOptions()
            .position(new LatLng(location.getLatitude() - 0.0005, location.getLongitude() + 0.0005))
            .title(creature.getName())
            .icon(BitmapDescriptorFactory.fromBitmap(b)));
  }
Пример #3
0
  @Override
  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMyLocationEnabled(true);

    Bundle extras = getIntent().getExtras();
    float[] lats = {}, lngs = {};
    String[] titles = {}, snippets = {};
    int[] beers = {};

    if (null != extras) {
      lats = extras.getFloatArray("Latitudes");
      lngs = extras.getFloatArray("Longitudes");
      titles = extras.getStringArray("Titles");
      snippets = extras.getStringArray("Snippets");
      beers = extras.getIntArray("Beers");
    }
    googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());

    LatLng ll = null;
    for (int i = 0; i < titles.length; i++) {
      ll = new LatLng(lats[i], lngs[i]);

      MarkerOptions mark = new MarkerOptions().position(ll).title(titles[i]).snippet(snippets[i]);

      // Other color if beer has been drunk.
      // The argument to defaultMarker() takes a float between 0-360.0,
      // check BitmapDescriptorFactory.HUE_*.
      // It is possible to create a BitmapDescriptor from drawables etc.
      BitmapDescriptor icon;
      if (i < beers.length && 0 < beers[i]) {
        icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN);
      } else {
        icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
      }
      mark.icon(icon);

      // Add a marker and set the number of beers drunk
      Marker marker = mMap.addMarker(mark);
      beerMap.put(marker, (beers.length > i ? beers[i] : 0));
    }

    /* Add propellern */
    BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.proppeller);
    Bitmap b = bd.getBitmap();
    Bitmap bhalfsize = Bitmap.createScaledBitmap(b, b.getWidth() / 2, b.getHeight() / 2, false);
    MarkerOptions propellern =
        new MarkerOptions()
            .position(PROPELLERN)
            .icon(BitmapDescriptorFactory.fromBitmap(bhalfsize));
    mMap.addMarker(propellern);

    /* See zoom */
    if (null == ll || 1 < titles.length) {
      // Zoom from far 2.0 (zoomed out) to close 21.0 (zoomed in)
      mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(PROPELLERN, 12.2f));
    } else {
      mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 12.2f));
    }
  }
    /**
     * Returns an icon for the vehicle that should be shown on the map
     *
     * @param isRealtime true if the marker shown indicate real-time info, false if it should
     *     indicate schedule
     * @param status the vehicles status to add to the map
     * @param response the response which contained the provided status
     * @return an icon for the vehicle that should be shown on the map
     */
    private BitmapDescriptor getVehicleIcon(
        boolean isRealtime, ObaTripStatus status, ObaTripsForRouteResponse response) {
      int colorResource;
      Resources r = Application.get().getResources();

      if (isRealtime) {
        long deviationMin = TimeUnit.SECONDS.toMinutes(status.getScheduleDeviation());
        colorResource = ArrivalInfo.computeColorFromDeviation(deviationMin);
      } else {
        colorResource = R.color.stop_info_scheduled_time;
      }
      int color = r.getColor(colorResource);
      double direction = MathUtils.toDirection(status.getOrientation());
      int halfWind = MathUtils.getHalfWindIndex((float) direction, NUM_DIRECTIONS - 1);
      // Log.d(TAG, "VehicleId=" + status.getVehicleId() + ", orientation= " +
      // status.getOrientation() + ", direction=" + direction + ", halfWind= " + halfWind + ",
      // deviation=" + status.getScheduleDeviation());

      String key = createBitmapCacheKey(halfWind, colorResource);
      Bitmap b = getBitmapFromCache(key);
      if (b == null) {
        // Cache miss - create Bitmap and add to cache
        b = UIUtils.colorBitmap(vehicle_icons[halfWind], color);
        addBitmapToCache(key, b);
      }
      return BitmapDescriptorFactory.fromBitmap(b);
    }
Пример #5
0
 @Override
 protected void onBeforeClusterItemRendered(MarkerData item, MarkerOptions markerOptions) {
   super.onBeforeClusterItemRendered(item, markerOptions);
   imageView.setImageResource(item.getProfilePhoto());
   Bitmap icon = iconGenerator.makeIcon();
   markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(item.getName());
 }
Пример #6
0
  public void UpdateMarker() {
    marker.setTitle(
        (isInvoln() ? "Powered up " : "")
            + PlayerType.getTypeString(type)
            + " "
            + (local ? "You" : name));
    int drawableID = PlayerType.getDrawableID(type);

    Bitmap bmp = BitmapFactory.decodeResource(Game.getAppContext().getResources(), drawableID);

    if (bmp == null) {
      return;
    }

    double aspect = bmp.getWidth() / (double) bmp.getHeight();
    marker.setIcon(
        BitmapDescriptorFactory.fromBitmap(
            Bitmap.createScaledBitmap(bmp, (int) (100 * aspect), 100, false)));
    marker.setAlpha(isCooldown() ? 0.5f : 1f);
    marker.setVisible(true);
    marker.setPosition(new LatLng(latitude, longitude));
    marker.setSnippet("Score: " + score);
    accuracyCircle.setCenter(new LatLng(latitude, longitude));
    accuracyCircle.setRadius(accuracy);
  }
Пример #7
0
 private static void createMarker(Context context, int resource, String name) {
   Bitmap b = BitmapFactory.decodeResource(context.getResources(), resource);
   descriptors.put(
       name,
       BitmapDescriptorFactory.fromBitmap(
           Bitmap.createScaledBitmap(b, b.getWidth() * 1, b.getHeight() * 1, false)));
   descriptors.put(
       name + "_m",
       BitmapDescriptorFactory.fromBitmap(
           Bitmap.createScaledBitmap(
               b, (int) (b.getWidth() * 0.75), (int) (b.getHeight() * 0.75), false)));
   descriptors.put(
       name + "_s",
       BitmapDescriptorFactory.fromBitmap(
           Bitmap.createScaledBitmap(
               b, (int) (b.getWidth() * 0.5), (int) (b.getHeight() * 0.5), false)));
 }
Пример #8
0
    @Override
    protected void onPostExecute(Bitmap bitmapResult) {

      super.onPostExecute(bitmapResult);
      if (bitmapResult == null || cancelAsyncTasks || !isAdded() || map == null) {
        return;
      }
      Marker marker = markerMap.get(email);
      Boolean isNew = false;
      if (marker != null) {
        Log.d(TAG, "onPostExecute - updating marker: " + email);
        marker.setPosition(latLng);
        marker.setSnippet(time);
        marker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmapResult));

      } else {
        Log.d(TAG, "onPostExecute - creating marker: " + email);
        marker =
            map.addMarker(
                new MarkerOptions()
                    .position(latLng)
                    .title(email)
                    .snippet(time)
                    .icon(BitmapDescriptorFactory.fromBitmap(bitmapResult)));
        Log.d(TAG, "onPostExecute - marker created");
        markerMap.put(email, marker);
        Log.d(TAG, "onPostExecute - marker in map stored. markerMap: " + markerMap.size());
        isNew = true;
      }

      if (marker.getTitle().equals(MainApplication.emailBeingTracked)) {
        marker.showInfoWindow();
        Log.d(TAG, "onPostExecute - showInfoWindow open");
        if (isNew) {
          map.moveCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 16));
        } else {
          map.moveCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));
        }
      } else if (firstTimeZoom
          && MainApplication.emailBeingTracked == null
          && MainApplication.userAccount != null
          && marker.getTitle().equals(MainApplication.userAccount)) {
        firstTimeZoom = false;
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 16));
      }
    }
Пример #9
0
 private BitmapDescriptor generateIcon(float heading, int type) {
   Bitmap planeBitmap = getBitmap(type);
   Matrix matrix = new Matrix();
   matrix.postRotate(heading);
   return BitmapDescriptorFactory.fromBitmap(
       Bitmap.createBitmap(
           planeBitmap, 0, 0, planeBitmap.getWidth(), planeBitmap.getHeight(), matrix, true));
 }
Пример #10
0
 @Override
 protected void onPostExecute(Bitmap result) {
   if (dialog.isShowing()) dialog.dismiss();
   bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(result);
   getMap();
   getCoverage();
   handleIntent(MapsLteCoverage.this.getIntent());
 }
Пример #11
0
 public void setMarkerImage(Marker marker, GeoObject geoObject) {
   if (marker == null || geoObject == null) {
     return;
   }
   Bitmap btm = getBitmapFromGeoObject(geoObject);
   if (btm != null) {
     marker.setIcon(BitmapDescriptorFactory.fromBitmap(btm));
   }
 }
Пример #12
0
  public MarkerOptions getMarkerOptions(Context context, LatLng latLng, int i, int drawableRes) {
    Bitmap glassVoll = BitmapFactory.decodeResource(context.getResources(), drawableRes);
    Bitmap glassVollKlein =
        Bitmap.createScaledBitmap(
            glassVoll, glassVoll.getWidth() / 2, glassVoll.getHeight() / 2, false);

    return new MarkerOptions()
        .position(latLng)
        .title(String.valueOf(i))
        .icon(BitmapDescriptorFactory.fromBitmap(glassVollKlein));
  }
 private BitmapDescriptor getIcon() {
   if (hasCustomMarkerView) {
     // creating a bitmap from an arbitrary view
     return BitmapDescriptorFactory.fromBitmap(createDrawable());
   } else if (iconResourceId != null) {
     // use local image as a marker
     return BitmapDescriptorFactory.fromResource(iconResourceId);
   } else {
     // render the default marker pin
     return BitmapDescriptorFactory.defaultMarker(this.markerHue);
   }
 }
 /**
  * Called before the marker for a Cluster is added to the map. The default implementation draws a
  * circle with a rough count of the number of items.
  */
 protected void onBeforeClusterRendered(Cluster<T> cluster, MarkerOptions markerOptions) {
   int bucket = getBucket(cluster);
   BitmapDescriptor descriptor = mIcons.get(bucket);
   if (descriptor == null) {
     mColoredCircleBackground.getPaint().setColor(getColor(bucket));
     descriptor =
         BitmapDescriptorFactory.fromBitmap(mIconGenerator.makeIcon(getClusterText(bucket)));
     mIcons.put(bucket, descriptor);
   }
   // TODO: consider adding anchor(.5, .5) (Individual markers will overlap more often)
   markerOptions.icon(descriptor);
 }
  @Override
  protected MarkerOptions[] doInBackground(String... nazwaMarkera) {

    MarkerOptions[] opcjeMarkerow = new MarkerOptions[nazwaMarkera.length];
    for (int i = 0; i < nazwaMarkera.length; i++) {
      LatLng wspolrzedne = new LatLng(tablicaSzerokosciAlbumow[i], tablicaDlugosciAlbumow[i]);
      sciezkaDoZdjecia = getFirstPhotoInAlbum(nazwaMarkera[i]);
      if (trybaEdycja == true) {
        opcjeMarkerow[i] =
            new MarkerOptions()
                .alpha(70)
                .position(wspolrzedne)
                .draggable(true)
                .icon(
                    BitmapDescriptorFactory.fromBitmap(
                        getMarkerBitmapFromView(
                            mCustomMarkerView,
                            mMarkerImageView,
                            R.drawable.folder_multiple_image,
                            sciezkaDoZdjecia)))
                .title("Zobacz tylko te zdjęcia");
      } else {
        opcjeMarkerow[i] =
            new MarkerOptions()
                .alpha(70)
                .position(wspolrzedne)
                .draggable(false)
                .icon(
                    BitmapDescriptorFactory.fromBitmap(
                        getMarkerBitmapFromView(
                            mCustomMarkerView,
                            mMarkerImageView,
                            R.drawable.folder_multiple_image,
                            sciezkaDoZdjecia)))
                .title("Zobacz tylko te zdjęcia");
      }
    }

    return opcjeMarkerow;
  }
Пример #16
0
    public HostRenderer() {
      super(getApplicationContext(), mMap, mClusterManager);

      View sameLocationMultiHostClusterView =
          getLayoutInflater().inflate(R.layout.same_location_cluster_marker, null);
      View singleHostMarkerView = getLayoutInflater().inflate(R.layout.location_marker, null);
      mSingleLocationClusterIconGenerator.setContentView(sameLocationMultiHostClusterView);
      mSingleLocationClusterIconGenerator.setBackground(null);
      mSingleHostIconGenerator.setContentView(singleHostMarkerView);
      mSingleHostIconGenerator.setBackground(null);
      mSingleHostBitmapDescriptor =
          BitmapDescriptorFactory.fromBitmap(mSingleHostIconGenerator.makeIcon());
    }
Пример #17
0
 /**
  * Returns the BitMapDescriptor for a particular bus stop icon, based on the stop direction
  *
  * @param direction Bus stop direction, obtained from ObaStop.getDirection() and defined in
  *     constants in this class
  * @return BitmapDescriptor for the bus stop icon that should be used for that direction
  */
 private static BitmapDescriptor getBitmapDescriptorForBusStopDirection(String direction) {
   if (direction.equals(NORTH)) {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[0]);
   } else if (direction.equals(NORTH_WEST)) {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[1]);
   } else if (direction.equals(WEST)) {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[2]);
   } else if (direction.equals(SOUTH_WEST)) {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[3]);
   } else if (direction.equals(SOUTH)) {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[4]);
   } else if (direction.equals(SOUTH_EAST)) {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[5]);
   } else if (direction.equals(EAST)) {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[6]);
   } else if (direction.equals(NORTH_EAST)) {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[7]);
   } else if (direction.equals(NO_DIRECTION)) {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[8]);
   } else {
     return BitmapDescriptorFactory.fromBitmap(bus_stop_icons[8]);
   }
 }
  public void addMarker(Airplane airplane) {
    AirplanePosition position = airplane.getLastPosition();
    LatLng location = new LatLng(position.getLatitude(), position.getLongitude());
    float angle = (float) airplane.getHead() - map.getCameraPosition().bearing;

    MarkerOptions options = new MarkerOptions();
    options.position(location);
    options.title(airplane.getHex());
    options.icon(BitmapDescriptorFactory.fromBitmap(getAirplaneIcon(angle)));
    options.anchor(0.5f, 0.5f);

    Marker marker = map.addMarker(options);
    markers.add(marker);
  }
  public void updateMarker(Airplane airplane) {
    for (Marker m : markers) {
      boolean infoShow = m.isInfoWindowShown();
      if (m.getTitle().equals(airplane.getHex())) {
        AirplanePosition position = airplane.getLastPosition();
        LatLng location = new LatLng(position.getLatitude(), position.getLongitude());
        float angle = (float) airplane.getHead() + map.getCameraPosition().bearing;
        m.setPosition(location);
        m.setIcon(BitmapDescriptorFactory.fromBitmap(getAirplaneIcon(angle)));

        if (infoShow) m.showInfoWindow();
        break;
      }
    }
  }
  private MarkerOptions createMarker(ReadableMap markerJson) {
    MarkerOptions options = new MarkerOptions();
    options.position(
        new LatLng(
            markerJson.getMap("coordinates").getDouble("lat"),
            markerJson.getMap("coordinates").getDouble("lng")));

    if (markerJson.hasKey("title")) {
      options.title(markerJson.getString("title"));
    }
    if (markerJson.hasKey("color")) {
      options.icon(BitmapDescriptorFactory.defaultMarker((float) markerJson.getDouble("color")));
    }
    if (markerJson.hasKey("snippet")) {
      options.snippet(markerJson.getString("snippet"));
    }
    if (markerJson.hasKey("icon")) {
      String varName = "";
      ReadableType iconType = markerJson.getType("icon");
      if (iconType.compareTo(ReadableType.Map) >= 0) {
        ReadableMap icon = markerJson.getMap("icon");
        try {
          int resId = getResourceDrawableId(icon.getString("uri"));
          Bitmap image = BitmapFactory.decodeResource(reactContext.getResources(), resId);

          options.icon(
              BitmapDescriptorFactory.fromBitmap(
                  Bitmap.createScaledBitmap(
                      image, icon.getInt("width"), icon.getInt("height"), true)));
        } catch (Exception e) {
          varName = icon.getString("uri");
        }
      } else if (iconType.compareTo(ReadableType.String) >= 0) {
        varName = markerJson.getString("icon");
      }
      if (!varName.equals("")) {
        // Changing marker icon to use resource
        int resourceValue = getResourceDrawableId(varName);
        Log.i(REACT_CLASS, varName + markerJson.toString());
        options.icon(BitmapDescriptorFactory.fromResource(resourceValue));
      }
    }
    if (markerJson.hasKey("anchor")) {
      ReadableArray anchor = markerJson.getArray("anchor");
      options.anchor((float) anchor.getDouble(0), (float) anchor.getDouble(1));
    }
    return options;
  }
Пример #21
0
  private void drawImageOverMap() {

    // BitmapFactory.Options options = new BitmapFactory.Options();
    // options.inSampleSize = 2;
    // Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
    // R.drawable.trails_nomarkup,options);

    Bitmap bitmap = DisplayManager.getInstance().getCanvasBitmap();

    image = BitmapDescriptorFactory.fromBitmap(bitmap);
    LatLngBounds bounds = new LatLngBounds(southwest, northeast);

    mGroundOverlay =
        googleMap.addGroundOverlay(
            new GroundOverlayOptions().image(image).transparency(0).positionFromBounds(bounds));
  }
Пример #22
0
    @Override
    protected void onBeforeClusterRendered(
        Cluster<HostBriefInfo> cluster, MarkerOptions markerOptions) {

      if (clusterLocationStatus(cluster) == ClusterStatus.all) {
        int size = cluster.getSize();
        BitmapDescriptor descriptor = mIcons.get(size);
        if (descriptor == null) {
          // Cache new bitmaps
          descriptor =
              BitmapDescriptorFactory.fromBitmap(
                  mSingleLocationClusterIconGenerator.makeIcon(String.valueOf(size)));
          mIcons.put(size, descriptor);
        }
        markerOptions.icon(descriptor);
      } else {
        super.onBeforeClusterRendered(cluster, markerOptions);
      }
    }
Пример #23
0
  public void closestMark(List<MarkerOptions> markerOptionsList, View closestMarker) {

    int R;
    double x, y, distance;
    //        double currentLatitude = tempLocation.getLatitude();
    //        double currentLongitude = tempLocation.getLongitude();
    //
    //        LatLng latLng = new LatLng(currentLatitude, currentLongitude);
    LatLng latLngList;

    int closestNumber = 0;

    Log.i("closestNumber", "wbijam do obliczania najblizszego");

    for (int i = 0; i < markerOptionsList.size(); i++) {

      latLngList = markerOptionsList.get(i).getPosition();

      R = 6371; // km
      x = (latLngList.longitude - b) * Math.cos((a + latLngList.latitude) / 2);
      y = (latLngList.latitude - a);
      distance = Math.sqrt(x * x + y * y) * R;

      Log.i("distance", "" + distance);

      if (distance < closestDistance) {
        closestNumber = i;

        closestDistance = distance;
        Log.i("closestNumber", "" + i);
      }
    }

    markerOptionsList
        .get(closestNumber)
        .icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, closestMarker)));

    mMap.addMarker(markerOptionsList.get(closestNumber));

    Log.i("ab", " " + a);
    Log.i("ab", " " + b);
  }
    @Override
    protected void onBeforeClusterRendered(Cluster<Case> cluster, MarkerOptions markerOptions) {
      ArrayList<Case> case_array = new ArrayList<Case>(cluster.getItems());
      float avg = getAverageUnitPrice(case_array);
      int drawable_id = R.drawable.yellow_cluster_marker;

      if (avg <= average_unit_price_90p) {
        drawable_id = R.drawable.blue_cluster_marker;
      } else if (avg >= average_unit_price_110p) {
        drawable_id = R.drawable.red_cluster_marker;
      }

      DecimalFormat df = new DecimalFormat("0.0");
      float compare_value = Float.parseFloat(df.format(avg));

      if (Float.compare(avg, compare_value) > 0) {
        avg = Float.parseFloat(df.format(compare_value + 0.1f));
      } else {
        avg = compare_value;
      }

      Bitmap icon = generateMarkerIcon(drawable_id, String.valueOf(avg) + "萬/坪");
      markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
    }
Пример #25
0
    @Override
    protected void onBeforeClusterRendered(
        Cluster<MarkerData> cluster, MarkerOptions markerOptions) {
      super.onBeforeClusterRendered(cluster, markerOptions);
      List<Drawable> profilePhotos = new ArrayList<Drawable>(Math.min(4, cluster.getSize()));
      int width = dimension;
      int height = dimension;

      for (MarkerData markerData : cluster.getItems()) {
        // Draw 4 at most.
        if (profilePhotos.size() == 4) break;
        Drawable drawable =
            ContextCompat.getDrawable(getApplicationContext(), markerData.getProfilePhoto());
        //                        getResources().getDrawable(markerData.getProfilePhoto());
        drawable.setBounds(0, 0, width, height);
        profilePhotos.add(drawable);
      }
      MultiDrawable multiDrawable = new MultiDrawable(profilePhotos);
      multiDrawable.setBounds(0, 0, width, height);

      clusterImageView.setImageDrawable(multiDrawable);
      Bitmap icon = clusterIconGenerator.makeIcon(String.valueOf(cluster.getSize()));
      markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
    }
Пример #26
0
  private void updateMap() {
    if (map == null) {
      return;
    }
    Station station = Db.get().getStop(adapter.getStops().get(0).id);
    LatLng ll =
        new LatLng(Double.parseDouble(station.getLat()), Double.parseDouble(station.getLng()));
    PolylineOptions poly = new PolylineOptions();
    LatLngBounds llb = new LatLngBounds(ll, ll);
    // map.setMapType(GoogleMap.MAP_TYPE_NONE);
    int dimen = (int) getResources().getDimension(R.dimen.fab_size_mini) / 3;
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    int color = Color.RED;
    Bitmap bitmap = Bitmap.createBitmap(dimen, dimen, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    paint.setStyle(Paint.Style.FILL_AND_STROKE);
    Station stationA = null, stationB = null;
    Calendar now = Calendar.getInstance();

    TripInfo.Stop previous = null;
    float percent = 0;
    for (TripInfo.Stop stop : adapter.getStops()) {

      canvas.clipRect(0, 0, canvas.getWidth(), canvas.getHeight());
      station = Db.get().getStop(stop.id);
      Log.d(
          TAG,
          station.getName()
              + " "
              + station.getLat()
              + ","
              + station.getLng()
              + " "
              + stop.depart.getTime());
      paint.setColor(color);

      if (now.after(stop.depart)) {
        stationA = station;
        previous = stop;
      } else {
        if (stationB == null && stationA != station) {
          stationB = station;
          if (previous == null) {
            percent = 0;
          } else if (previous.depart == null || stop.arrive == null) {

          } else {
            long max = stop.arrive.getTimeInMillis() - previous.depart.getTimeInMillis();
            long curr = stop.arrive.getTimeInMillis() - System.currentTimeMillis();

            if (curr <= 0) {
              percent = 0;
            } else {
              percent = 1 - (curr / (float) max);
            }
          }
        }
      }
      canvas.drawCircle(
          bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
      station = Db.get().getStop(stop.id);
      LatLng latLng =
          new LatLng(Double.parseDouble(station.getLat()), Double.parseDouble(station.getLng()));
      llb = llb.including(latLng);

      if (markers.get(stop) != null) {
        markers.get(stop).remove();
      }
      Marker hamburg =
          map.addMarker(
              new MarkerOptions()
                  .position(latLng)
                  .anchor(0.5f, 0.5f)
                  .icon(BitmapDescriptorFactory.fromBitmap(bitmap)));
      markers.put(stop, hamburg);
      poly.add(latLng);
    }

    if (polyline != null) {
      polyline.remove();
    } else {
      map.moveCamera(CameraUpdateFactory.newLatLngBounds(llb, dimen));
    }
    // poly.
    polyline = map.addPolyline(poly);

    if (stationA == null) {
      return;
    }
    if (stationB == null) {
      stationB = stationA;
    }

    Location location = new Location(LocationManager.GPS_PROVIDER);
    location.setLatitude(Double.parseDouble(stationA.getLat()));
    location.setLongitude(Double.parseDouble(stationA.getLng()));

    Location location2 = new Location(LocationManager.GPS_PROVIDER);
    location2.setLatitude(Double.parseDouble(stationB.getLat()));
    location2.setLongitude(Double.parseDouble(stationB.getLng()));
    //        var θ = Number(brng).toRadians();
    //        var δ = Number(dist) / this.radius; // angular distance in radians
    //
    //        var φ1 = this.lat.toRadians();
    //        var λ1 = this.lon.toRadians();
    //
    //        var φ2 = Math.asin( Math.sin(φ1)*Math.cos(δ) +
    //                Math.cos(φ1)*Math.sin(δ)*Math.cos(θ) );
    //        var λ2 = λ1 + Math.atan2(Math.sin(θ)*Math.sin(δ)*Math.cos(φ1),
    //                Math.cos(δ)-Math.sin(φ1)*Math.sin(φ2));
    //        λ2 = (λ2+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180°

    double totalDist = location.distanceTo(location2);

    Log.d(TAG, "distance is " + totalDist + " percentage is " + percent);

    double dist = (percent * totalDist) / (6371.0 * 1000.0);

    double brng = Math.toRadians(location.bearingTo(location2));
    double lat1 = Math.toRadians(location.getLatitude());
    double lon1 = Math.toRadians(location.getLongitude());

    double lat2 =
        Math.asin(
            Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
    double a =
        Math.atan2(
            Math.sin(brng) * Math.sin(dist) * Math.cos(lat1),
            Math.cos(dist) - Math.sin(lat1) * Math.sin(lat2));
    System.out.println("a = " + a);
    double lon2 = lon1 + a;

    lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI;

    System.out.println(
        "Latitude = " + Math.toDegrees(lat2) + "\nLongitude = " + Math.toDegrees(lon2));
    MarkerOptions o =
        new MarkerOptions()
            .anchor(0.5f, 0.5f)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.new_blue_dot))
            .position(new LatLng(Math.toDegrees(lat2), Math.toDegrees(lon2)));
    if (me != null) {
      me.remove();
    }
    if (stationA != stationB) {
      me = map.addMarker(o);
    }
    Log.d(TAG, "new coordinates are " + lat2 + "," + lon2);
  }
Пример #27
0
    @Override
    protected Runnable doInBackground(CameraPosition... cameraPositions) {
      try {
        final Map<Takeoff, MarkerOptions> addMarkers = new HashMap<>();

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
        if (sharedPref.getBoolean("pref_map_show_takeoffs", true)) {
          LatLng latLng = cameraPositions[0].target;
          Location mapLocation = new Location(LocationManager.PASSIVE_PROVIDER);
          mapLocation.setLatitude(latLng.latitude);
          mapLocation.setLongitude(latLng.longitude);

          /* get the 25 nearest takeoffs */
          List<Takeoff> takeoffs =
              Database.getTakeoffs(
                  getActivity(), latLng.latitude, latLng.longitude, 25, false, true);

          /* add markers */
          for (Takeoff takeoff : takeoffs) {
            Bitmap bitmap =
                Bitmap.createBitmap(
                    markerBitmap.getWidth(), markerBitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint();
            if (!takeoff.isFavourite()) paint.setAlpha(123);
            canvas.drawBitmap(markerBitmap, 0, 0, paint);
            if (takeoff.hasNorthExit()) canvas.drawBitmap(markerNorthBitmap, 0, 0, paint);
            if (takeoff.hasNortheastExit()) canvas.drawBitmap(markerNortheastBitmap, 0, 0, paint);
            if (takeoff.hasEastExit()) canvas.drawBitmap(markerEastBitmap, 0, 0, paint);
            if (takeoff.hasSoutheastExit()) canvas.drawBitmap(markerSoutheastBitmap, 0, 0, paint);
            if (takeoff.hasSouthExit()) canvas.drawBitmap(markerSouthBitmap, 0, 0, paint);
            if (takeoff.hasSouthwestExit()) canvas.drawBitmap(markerSouthwestBitmap, 0, 0, paint);
            if (takeoff.hasWestExit()) canvas.drawBitmap(markerWestBitmap, 0, 0, paint);
            if (takeoff.hasNorthwestExit()) canvas.drawBitmap(markerNorthwestBitmap, 0, 0, paint);
            if (takeoff.getPilotsToday() > 0) canvas.drawBitmap(markerExclamation, 0, 0, paint);
            else if (takeoff.getPilotsLater() > 0)
              canvas.drawBitmap(markerExclamationYellow, 0, 0, paint);
            String snippet =
                getString(R.string.height)
                    + ": "
                    + takeoff.getHeight()
                    + "m\n"
                    + getString(R.string.distance)
                    + ": "
                    + (int) mapLocation.distanceTo(takeoff.getLocation()) / 1000
                    + "km";
            MarkerOptions markerOptions =
                new MarkerOptions()
                    .position(
                        new LatLng(
                            takeoff.getLocation().getLatitude(),
                            takeoff.getLocation().getLongitude()))
                    .title(takeoff.getName())
                    .snippet(snippet)
                    .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                    .anchor(0.5f, 0.875f);
            addMarkers.put(takeoff, markerOptions);
          }
        }

        /* remove markers that we didn't "add" */
        return new Runnable() {
          @Override
          public void run() {
            // remove markers that no longer should be visible
            for (Iterator<Map.Entry<String, Pair<Marker, Takeoff>>> iterator =
                    markers.entrySet().iterator();
                iterator.hasNext(); ) {
              Map.Entry<String, Pair<Marker, Takeoff>> entry = iterator.next();
              if (!addMarkers.containsKey(entry.getValue().second)) {
                entry.getValue().first.remove();
                iterator.remove();
              }
            }
            // add markers that should be visible
            for (Map.Entry<Takeoff, MarkerOptions> addEntry : addMarkers.entrySet()) {
              boolean alreadyShown = false;
              for (Map.Entry<String, Pair<Marker, Takeoff>> entry : markers.entrySet()) {
                if (addEntry.getKey().equals(entry.getValue().second)) {
                  alreadyShown = true;
                  break;
                }
              }
              if (!alreadyShown) {
                Marker marker = map.addMarker(addEntry.getValue());
                Pair<Marker, Takeoff> pair = new Pair<>(marker, addEntry.getKey());
                markers.put(marker.getId(), pair);
              }
            }
          }
        };
      } catch (Exception e) {
        Log.w(getClass().getName(), "doInBackground() failed unexpectedly", e);
      }
      return null;
    }
 public static BitmapDescriptor fromBitmap(Bitmap image) {
   return new BitmapDescriptor(
       com.google.android.gms.maps.model.BitmapDescriptorFactory.fromBitmap(image));
 }
Пример #29
0
  /**
   * Sets map camera zoom and places markers upon the given map's readiness. Tap: display station
   * name and station details. Long-Tap: launch turn-by-turn navigation (NavActivity) to selected
   * station.
   *
   * @param map The GoogleMap instance to display.
   */
  @Override
  public void onMapReady(GoogleMap map) {
    // Set camera zoom
    map.moveCamera(
        CameraUpdateFactory.newLatLngZoom(new LatLng(37.804697, -122.201255), (float) 9.5));

    // Iterate through all stations in the stationLatLngMap,
    // generating a Marker for each
    Set<Map.Entry<String, LatLng>> entries = stationLatLngMap.entrySet();
    Iterator<Map.Entry<String, LatLng>> iter = entries.iterator();

    for (int i = 0; i < stationLatLngMap.size(); i++) {
      Map.Entry<String, LatLng> entry = iter.next();
      LatLng val = entry.getValue();
      String stationName = entry.getKey();

      Marker mMarker =
          map.addMarker(
              new MarkerOptions()
                  .icon(
                      BitmapDescriptorFactory.fromBitmap(
                          generateIcon(R.drawable.marker_bartgo_logo_round, 2)))
                  .anchor(0.5f, 1.0f) /*Anchors the marker on the bottom center */
                  .position(val)
                  .title(stationName + " BART")
                  /*.snippet("ETA:  50 min | $6.50 | $13.00")*/
                  .snippet(generateSnippet(stationName))
                  .draggable(true));

      map.setOnMarkerDragListener(
          new GoogleMap.OnMarkerDragListener() {
            // Simulate long-click functionality
            @Override
            public void onMarkerDragStart(Marker marker) {
              Intent postSelectionIntent = new Intent(getBaseContext(), postSelection.class);

              // Retrieve destination based on marker being long-tapped on
              String stationKey = marker.getTitle();
              int len = stationKey.length();
              stationKey = stationKey.substring(0, len - 5);
              LatLng stationLatLng = getStationLatLng(stationKey);

              // Origin data
              Double origLat = Double.parseDouble(originStation.getLatitude());
              Double origLng = Double.parseDouble(originStation.getLongitude());
              // Dest data
              Double destLat = stationLatLng.latitude;
              Double destLng = stationLatLng.longitude;

              // Pass origin/destination extras
              postSelectionIntent.putExtra("origLat", origLat);
              postSelectionIntent.putExtra("origLng", origLng);
              postSelectionIntent.putExtra("destLat", destLat);
              postSelectionIntent.putExtra("destLng", destLng);
              postSelectionIntent.putExtra("destName", stationKey);
              postSelectionIntent.putExtra("origStation", originStation.getAbbreviation());
              startActivity(postSelectionIntent);
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
              // Nothing special to do
            }

            @Override
            public void onMarkerDrag(Marker marker) {
              // Do special to do
            }
          });
    }
  }
  public void addMarkers(List<GridPoint> gridPointList, List<PointEntity> pointEntityList) {
    clearMap();
    Marker m;
    LatLngBounds.Builder builder = new LatLngBounds.Builder();

    for (GridPoint gridPoint : gridPointList) {
      Bitmap icon =
          gridPoint.getScore() > 10
              ? gridPoint.getScore() > 20
                  ? BitmapFactory.decodeResource(getResources(), R.drawable.red_dot)
                  : BitmapFactory.decodeResource(getResources(), R.drawable.yellow_dot)
              : BitmapFactory.decodeResource(getResources(), R.drawable.green_dot);
      float hue =
          gridPoint.getScore() > 10
              ? gridPoint.getScore() > 20
                  ? BitmapDescriptorFactory.HUE_RED
                  : BitmapDescriptorFactory.HUE_YELLOW
              : BitmapDescriptorFactory.HUE_GREEN;

      markerOptions = new MarkerOptions();
      markerOptions.visible(true);
      markerOptions.position(
          new LatLng(
              gridPoint.getLocation().getLatitude().doubleValue(),
              gridPoint.getLocation().getLongitude().doubleValue()));
      markerOptions.draggable(false);
      markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
      // markerOptions.icon(BitmapDescriptorFactory.defaultMarker(hue));

      m = googleMap.addMarker(markerOptions);
      gridMap.put(m.getId(), gridPoint);
      builder.include(m.getPosition());
    }

    for (PointEntity pointEntity : pointEntityList) {
      Bitmap icon =
          pointEntity.getPointType().equals(PointType.PERSON)
              ? BitmapFactory.decodeResource(getResources(), R.drawable.man)
              : pointEntity.getPointType().equals(PointType.POLICE_STATION)
                  ? BitmapFactory.decodeResource(getResources(), R.drawable.police)
                  : BitmapFactory.decodeResource(getResources(), R.drawable.hospital);
      markerOptions = new MarkerOptions();
      markerOptions.visible(true);
      markerOptions.position(
          new LatLng(
              pointEntity.getLocation().getLatitude().doubleValue(),
              pointEntity.getLocation().getLongitude().doubleValue()));
      markerOptions.draggable(false);
      markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));

      m = googleMap.addMarker(markerOptions);
      pointMap.put(m.getId(), pointEntity);
      builder.include(m.getPosition());
    }

    if (gridPointList.size() > 1) {
      LatLngBounds bounds = builder.build();
      CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 0);
      googleMap.animateCamera(cu);
    } else if (gridPointList.size() > 0) {
      CameraPosition cameraPosition =
          new CameraPosition.Builder()
              .target(
                  new LatLng(
                      gridPointList.get(0).getLocation().getLatitude().doubleValue(),
                      gridPointList.get(0).getLocation().getLongitude().doubleValue()))
              .zoom(zoomLevel)
              .bearing(0)
              .tilt(45)
              .build();
      googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    markersDisplayed = true;
    heatmapDisplayed = false;
    clusterDisplayed = false;
  }