1
votes

I'm using mapbox-sdk android for location tracking. I want to add few custom markers to the map in specified location. But the below code doesn't works for me.

MarkerOptions options = new MarkerOptions();
options.title("pos");
IconFactory iconFactory = IconFactory.getInstance(MainActivity.this);
Icon icon = iconFactory.fromResource(R.drawable.home);
options.icon(icon);
options.position(new LatLng(80.27, 13.09));
mapboxMap.addMarker(options); 

I use mapox-sdk:6.0.1

1

1 Answers

0
votes

use this:

private fun addMarkerIconsToMap(loadedMapStyle: Style) {
    BitmapUtils.getBitmapFromDrawable(getDrawable(R.drawable.red_marker))?.let {
        loadedMapStyle.addImage("icon-id", it)
    }
    if(!locationList.isNullOrEmpty()){
        val feature: ArrayList<Feature> = ArrayList()
        for (x in 0 until locationList.size){
            feature.add(Feature.fromGeometry(Point.fromLngLat(locationList[x].long, locationList[x].lat)))
        }
        loadedMapStyle.addSource(GeoJsonSource("source-id",
            FeatureCollection.fromFeatures(feature)
            )
        )
        loadedMapStyle.addLayer(SymbolLayer("layer-id", "source-id").withProperties(
            iconImage("icon-id"),
            iconOffset(arrayOf(0f, -8f))
            )
        )
    }
}

inside locationList is Array of long: Double and lat: Double

YourActivity :

class YourActivity : AppCompatActivity(), OnMapReadyCallback {
    private lateinit var mapboxMap: MapboxMap
    ...
    
}

and then override :

override fun onMapReady(mapboxMap: MapboxMap) {
    mapboxMap.setStyle(Style.MAPBOX_STREETS){
        addMarkerIconsToMap(it)
    }

    this.mapboxMap = mapboxMap
}