Skip to content
This repository was archived by the owner on Oct 7, 2024. It is now read-only.
This repository was archived by the owner on Oct 7, 2024. It is now read-only.

Mapbox - Heatmap action item #560

Closed
Closed

Description

@dkdevpro

Here is the snippet which I used to get heatmap points when the user clicks on the map.

Feature list (featureList0) always comes as "empty"

private void addClusteredGeoJsonSource(final MapboxMap mapboxMap) {

    // Add a new source from our GeoJSON data and set the 'cluster' option to true.
    try {

      mapboxMap.addSource(
        // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes from
        // 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
        new GeoJsonSource("test",
          new URL("https://www.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson"),
          new GeoJsonOptions()
            .withCluster(true)
            .withClusterMaxZoom(15) // Max zoom to cluster points on
            .withClusterRadius(20) // Use small cluster radius for the heatmap look
        )
      );
    } catch (MalformedURLException malformedUrlException) {
      Log.e("heatmapActivity", "Check the URL " + malformedUrlException.getMessage());
    }

    // Use the earthquakes source to create four layers:
    // three for each cluster category, and one for unclustered points

    // Each point range gets a different fill color.
    final int[][] layers = new int[][]{
      new int[]{150, Color.parseColor("#E55E5E")},
      new int[]{20, Color.parseColor("#F9886C")},
      new int[]{0, Color.parseColor("#FBB03B")}
    };

    CircleLayer unclustered = new CircleLayer("points", "test");
    unclustered.setProperties(
      circleColor(Color.parseColor("#FBB03B")),
      circleRadius(20f),
      circleBlur(1f));
    unclustered.setFilter(
      neq("cluster", true)
    );
    mapboxMap.addLayerBelow(unclustered, "test1");

    for (int i = 0; i < layers.length; i++) {
      CircleLayer circles = new CircleLayer("cluster-" + i, "test");
      circles.setProperties(
        circleColor(layers[i][1]),
        circleRadius(70f),
        circleBlur(1f)
      );
      circles.setFilter(
        i == 0
          ? gte("point_count", layers[i][0]) :
          all(gte("point_count", layers[i][0]), lt("point_count", layers[i - 1][0]))
      );
      mapboxMap.addLayerBelow(circles, "test1");
    }
    final int diff = 50;
    mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
      @Override
      public void onMapClick(@NonNull LatLng point) {
        PointF pointf = mapboxMap.getProjection().toScreenLocation(point);
        RectF rectF = new RectF(pointf.x - diff, pointf.y - diff, pointf.x + diff, pointf.y + diff);

        List<Feature> featureList0 = mapboxMap.queryRenderedFeatures(rectF, "points");
        int i = 0;
        for (com.mapbox.services.commons.geojson.Feature feature : featureList0) {
//                    Log.d("Feature found with %1$s", feature.toJson());
          Log.d("heat_map","Feature:"+ feature.getProperties().toString());
          JsonElement media = feature.getProperty("mMedia");
          if(media != null) {
            Log.d("heat_map","Feature: media:" +media);
          } else {
            Log.d("heat_map","Feature: media-:null");
          }
          i++;
        }
      }
    });
  }

Activity

  1. zugaldia commented on Dec 1, 2017

    @zugaldia
    Member
  2. langsmith commented on Dec 16, 2017

    @langsmith
    Contributor

    @Dino9 , thanks for using Mapbox. Try the code below. I was able to get featureList0 to return a size of 1 if not more in the CreateHotspotsActivity demo app example.

    screen shot 2017-12-15 at 4 41 30 pm

    In this example, the returned list size seems to depend on the map camera zoom level and exactly where I tap. I encourage you to try the code below and then play around with the zoom and tap location.

    Also seems that you're not using the i int that you set with int i = 0; and then ++ in the for loop...

    private void addClusteredGeoJsonSource(final MapboxMap mapboxMap) {
        Log.d(TAG, "addClusteredGeoJsonSource: starting");
        try {
    
          mapboxMap.addSource(
            // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes from
            // 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
            new GeoJsonSource(GEOJSON_SOURCE_ID,
              new URL("https://www.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson"),
              new GeoJsonOptions()
                .withCluster(true)
                .withClusterMaxZoom(15) // Max zoom to cluster points on
                .withClusterRadius(20) // Use small cluster radius for the heatmap look
            )
          );
        } catch (MalformedURLException malformedUrlException) {
          Log.e("CreateHotspotsActivity", "Check the URL " + malformedUrlException.getMessage());
        }
    
        // Use the earthquakes source to create four layers:
        // three for each cluster category, and one for unclustered points
    
        // Each point range gets a different fill color.
        final int[][] layers = new int[][] {
          new int[] {150, Color.parseColor("#E55E5E")},
          new int[] {20, Color.parseColor("#F9886C")},
          new int[] {0, Color.parseColor("#FBB03B")}
        };
    
        CircleLayer unclustered = new CircleLayer(UNCLUSTERED_CIRCLE_LAYER_ID, GEOJSON_SOURCE_ID);
        unclustered.setProperties(
          circleColor(Color.parseColor("#FBB03B")),
          circleRadius(20f),
          circleBlur(1f));
        unclustered.setFilter(
          neq("cluster", true)
        );
        mapboxMap.addLayerBelow(unclustered, "test1");
    
        for (int i = 0; i < layers.length; i++) {
          CircleLayer circles = new CircleLayer("cluster-" + i, GEOJSON_SOURCE_ID);
          circles.setProperties(
            circleColor(layers[i][1]),
            circleRadius(70f),
            circleBlur(1f)
          );
          circles.setFilter(
            i == 0
              ? gte("point_count", layers[i][0]) :
              all(gte("point_count", layers[i][0]), lt("point_count", layers[i - 1][0]))
          );
          mapboxMap.addLayerBelow(circles, "test1");
        }
    
        final int diff = 100;
    
        mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
          @Override
          public void onMapClick(@NonNull LatLng point) {
            Log.d(TAG, "onMapClick: Clicked on map");
    
            PointF pointf = mapboxMap.getProjection().toScreenLocation(point);
            RectF rectF = new RectF(pointf.x - diff, pointf.y - diff, pointf.x + diff, pointf.y + diff);
    
            List<Feature> listOfFeatures = mapboxMap.queryRenderedFeatures(rectF, UNCLUSTERED_CIRCLE_LAYER_ID);
            Log.d(TAG, "onMapClick: listOfFeatures.size() = " + listOfFeatures.size());
    
            int i = 0;
    
            for (com.mapbox.services.commons.geojson.Feature feature : listOfFeatures) {
    //          Log.d("Feature found with %1$s", feature.toJson());
              Log.d("heat_map", "Feature:" + feature.getProperties().toString());
              JsonElement media = feature.getProperty("mMedia");
              if (media != null) {
                Log.d("heat_map", "Feature: media:" + media);
              } else {
                Log.d("heat_map", "Feature: media-:null");
              }
              i++;
            }
    
          }
        });
      }
  3. langsmith commented on Dec 16, 2017

    @langsmith
    Contributor

    @Dino9 , also meant to say that my code changes the list name from featureList0 to listOfFeatures. Also, you'll notice that I use static strings for the source/layer ids. I find that this helps to keep clear on what's what when doing runtime/data-driven styling. Anyways, here's the entire example's code for you to try. Features do return in your final for loop 👇

    screen shot 2017-12-15 at 4 47 32 pm

    public class CreateHotspotsActivity extends AppCompatActivity {
    
      private MapView mapView;
    
      private static String TAG = "CreateHotspotsActivity";
      private static String GEOJSON_SOURCE_ID = "GEOJSON_SOURCE_ID";
      private static String UNCLUSTERED_CIRCLE_LAYER_ID = "UNCLUSTERED_CIRCLE_LAYER_ID";
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // Mapbox access token is configured here. This needs to be called either in your application
        // object or in the same activity which contains the mapview.
        Mapbox.getInstance(this, getString(R.string.access_token));
    
        // This contains the MapView in XML and needs to be called after the access token is configured.
        setContentView(R.layout.activity_style_create_hotspots_points);
    
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(new OnMapReadyCallback() {
          @Override
          public void onMapReady(MapboxMap mapboxMap) {
    
            addClusteredGeoJsonSource(mapboxMap);
          }
        });
      }
    
      @Override
      public void onResume() {
        super.onResume();
        mapView.onResume();
      }
    
      @Override
      protected void onStart() {
        super.onStart();
        mapView.onStart();
      }
    
      @Override
      protected void onStop() {
        super.onStop();
        mapView.onStop();
      }
    
      @Override
      public void onPause() {
        super.onPause();
        mapView.onPause();
      }
    
      @Override
      public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
      }
    
      @Override
      protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
      }
    
      @Override
      protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
      }
    
      private void addClusteredGeoJsonSource(final MapboxMap mapboxMap) {
        Log.d(TAG, "addClusteredGeoJsonSource: starting");
        try {
    
          mapboxMap.addSource(
            // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes from
            // 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
            new GeoJsonSource(GEOJSON_SOURCE_ID,
              new URL("https://www.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson"),
              new GeoJsonOptions()
                .withCluster(true)
                .withClusterMaxZoom(15) // Max zoom to cluster points on
                .withClusterRadius(20) // Use small cluster radius for the heatmap look
            )
          );
        } catch (MalformedURLException malformedUrlException) {
          Log.e("CreateHotspotsActivity", "Check the URL " + malformedUrlException.getMessage());
        }
    
        // Use the earthquakes source to create four layers:
        // three for each cluster category, and one for unclustered points
    
        // Each point range gets a different fill color.
        final int[][] layers = new int[][] {
          new int[] {150, Color.parseColor("#E55E5E")},
          new int[] {20, Color.parseColor("#F9886C")},
          new int[] {0, Color.parseColor("#FBB03B")}
        };
    
        CircleLayer unclustered = new CircleLayer(UNCLUSTERED_CIRCLE_LAYER_ID, GEOJSON_SOURCE_ID);
        unclustered.setProperties(
          circleColor(Color.parseColor("#FBB03B")),
          circleRadius(20f),
          circleBlur(1f));
        unclustered.setFilter(
          neq("cluster", true)
        );
        mapboxMap.addLayerBelow(unclustered, "test1");
    
        for (int i = 0; i < layers.length; i++) {
          CircleLayer circles = new CircleLayer("cluster-" + i, GEOJSON_SOURCE_ID);
          circles.setProperties(
            circleColor(layers[i][1]),
            circleRadius(70f),
            circleBlur(1f)
          );
          circles.setFilter(
            i == 0
              ? gte("point_count", layers[i][0]) :
              all(gte("point_count", layers[i][0]), lt("point_count", layers[i - 1][0]))
          );
          mapboxMap.addLayerBelow(circles, "test1");
        }
    
        final int diff = 100;
    
        mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
          @Override
          public void onMapClick(@NonNull LatLng point) {
            Log.d(TAG, "onMapClick: Clicked on map");
    
            PointF pointf = mapboxMap.getProjection().toScreenLocation(point);
            RectF rectF = new RectF(pointf.x - diff, pointf.y - diff, pointf.x + diff, pointf.y + diff);
    
            List<Feature> listOfFeatures = mapboxMap.queryRenderedFeatures(rectF, UNCLUSTERED_CIRCLE_LAYER_ID);
            Log.d(TAG, "onMapClick: listOfFeatures.size() = " + listOfFeatures.size());
    
            int i = 0;
    
            for (com.mapbox.services.commons.geojson.Feature feature : listOfFeatures) {
    //          Log.d("Feature found with %1$s", feature.toJson());
              Log.d(TAG, "Feature:" + feature.getProperties().toString());
              JsonElement media = feature.getProperty("mMedia");
              if (media != null) {
                Log.d(TAG, "Feature: media:" + media);
              } else {
                Log.d(TAG, "Feature: media-:null");
              }
              i++;
            }
          }
        });
      }
    }
  4. langsmith commented on Dec 16, 2017

    @langsmith
    Contributor

    I consider this solved. Please re-open if there's still an issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions