What is the best way to add markers on MapBox?

廉价感情. 提交于 2021-01-25 06:55:29

问题


As most of you know, mapbox.addMarker() is deprecated! I tried to figure the new way to add markers which are using Symbol Layer

I'm using this code, it is working for me! but it re-define the Style of the map every time I want to add a marker

here is the code:

 //Add Marker to the Map
    public void addMarker(@NonNull LatLng point) {
        Feature feature = Feature.fromGeometry(Point.fromLngLat(point.getLongitude(), point.getLatitude()));
        mapboxMap
                .setStyle(new Style.Builder()
                        .fromUri("mapbox://styles/mapbox/cjf4m44iw0uza2spb3q0a7s41")
                        .withImage(ICON_ID, marker)
                        .withSource(new GeoJsonSource(SOURCE_ID, feature))
                        .withLayer(new SymbolLayer(LAYER_ID, SOURCE_ID)
                                .withProperties(PropertyFactory.iconImage(ICON_ID),
                                        iconAllowOverlap(true),
                                        iconIgnorePlacement(true),
                                        iconOffset(new Float[]{0f, -9f}))));

    }

So, I was wondering if there is a correct or a better way to add markers on the latest MapBox SDK 8.5.0

Thanks!


回答1:


mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
                    @Override
                    public void onStyleLoaded(@NonNull final Style style) {
                     AddSanciangkoStreet(style);
                     SanciangkoStreetMarker();
             }
  }

private void AddSanciangkoStreet(@NonNull Style style) {
        style.addImage("sanciangko-street",
                BitmapUtils.getBitmapFromDrawable(getResources().getDrawable(R.drawable.floodicon)));

        style.addSource(new GeoJsonSource("sanciangkoFlood1-source-id"));

        style.addLayer(new SymbolLayer("sanciangkoFlood1-layer-id", "sanciangkoFlood1-source-id").withProperties(
                iconImage("sanciangko-street"),
                iconIgnorePlacement(true),
                iconAllowOverlap(true),
                iconSize(1f)
        ));
}

private void SanciangkoStreetMarker() {
        if (map.getStyle() != null) {
            GeoJsonSource sanciangkoFlood1 = map.getStyle().getSourceAs("sanciangkoFlood1-source-id");
            if (sanciangkoFlood1 != null) {
                sanciangkoFlood1.setGeoJson(FeatureCollection.fromFeature(
                        Feature.fromGeometry(Point.fromLngLat(123.895801, 10.297237))
                ));
            }
        }
}


来源:https://stackoverflow.com/questions/59499869/what-is-the-best-way-to-add-markers-on-mapbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!