mapboxmarkerandroid-gpsmapbox-androidcurrentlocation

Set Marker to Current Location in Android using Mapbox-sdk v8.6.1


I am using the updated sdk of Mapbox. But I couldn't add marker to current position. Moreover I don't have the latitude and longitude of current location. I am just using locationComponent to show the current position. It will be very helpful if anyone raise your helping hands.. Thanks in advance.


Solution

  • https://docs.mapbox.com/help/tutorials/android-location-listening/ shows how to track the device location.

    If that's too complicated or you don't need to constantly track location, you can do Location lastKnownLocation = mapboxMap.getLocationComponent().getLastKnownLocation(); once the LocationComponent is set up (https://docs.mapbox.com/android/maps/examples/show-a-users-location/).

    Location lastKnownLocation = mapboxMap.getLocationComponent().getLastKnownLocation();
    
    lastKnownLocation.getLatitude();
    lastKnownLocation.getLongitude();
    

    Now that you have the coordinates, you can add a SymbolLayer or add the new coordinates to an existing SymbolLayer's GeoJSON.

    https://docs.mapbox.com/android/maps/examples/marker-symbol-layer/

    How to update the SymbolLayer GeoJSON so that a new marker appears:

    map.getStyle(new Style.OnStyleLoaded() {
      @Override
      public void onStyleLoaded(@NonNull Style style) {
    
        featureList.add(Feature.fromGeometry(Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude())));
    
        FeatureCollection newFeatureCollection = FeatureCollection.fromFeatures(featureList);
    
        GeoJsonSource source = style.getSourceAs("symbol-layer-source-id");
        if (source != null) {
          source.setGeoJson(newFeatureCollection);
        }
    
    
      }
    });