好吧,显然有一种方法可以使用 Mapbox for Android SDK 来做我想做的事情。方法是这样的:
- 使用 GeoJson 文件加载点(标记)(添加数据源)
- 包括标记的图标(Mapbox 提供了广泛的默认标记https://www.mapbox.com/maki-icons/)
- 将 GeoJson 点与图标相关联(因此每个点至少与一个图标相关,但可能是您希望所有标记都使用相同的图标)(添加视觉表示)
- 添加 onClick 事件侦听器以检测已单击的点(添加交互性)
1.使用 GeoJson 文件加载点(标记)(添加数据源)
URL geoJsonUrl = new URL("https://your-website.com/list.json");
final GeoJsonSource geoJsonSource = new GeoJsonSource("geojson-source", geoJsonUrl);
mapboxMap.addSource(geoJsonSource);
2.包括标记的图标(Mapbox 提供了广泛的默认标记https://www.mapbox.com/maki-icons/)(添加视觉表示)
Bitmap marker_type1_icon = BitmapFactory.decodeResource(getResources(), R.drawable.marker_type1_icon);
mapboxMap.addImage("marker_type1", marker_type1_icon);
Bitmap marker_type2_icon = BitmapFactory.decodeResource(getResources(), R.drawable.marker_type2_icon);
mapboxMap.addImage("marker_type2", marker_type2_icon);
3.将 GeoJson 点与图标相关联(因此每个点至少与一个图标相关,但可能是您希望所有标记都使用相同的图标)(添加视觉表示)
SymbolLayer symbolLayer = new SymbolLayer("layer-id", "geojson-source");
symbolLayer.setProperties(
// This is the bit that makes the map to display an icon or another. "poi" is a property of a Point in a GeoJSON document.
// If you enclosed between keys,, it will introduce the value of the poi property.
// If you want a fixed icon for all markers, change this for "marker_type1", following my example from point 2.
PropertyFactory.iconImage("{poi}"),
// With this property we will show which Point was clicked, making the icon look bigger
PropertyFactory.iconSize(
Function.property(
"selected",
Stops.categorical(
Stop.stop(true, PropertyFactory.iconSize(2.0f)),
Stop.stop(false, PropertyFactory.iconSize(1.0f))
)
)
)
);
mapboxMap.addLayer(symbolLayer);
4.添加onClick事件监听器以检测点击了哪个点(添加交互性)
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
PointF screenPoint = mapboxMap.getProjection().toScreenLocation(point);
List<Feature> features = mapboxMap.queryRenderedFeatures(screenPoint, "layer-id");
if (!features.isEmpty()) {
Feature selectedFeature = features.get(0);
selectedFeature.getProperties().addProperty("selected", true);
String title = selectedFeature.getStringProperty("title");
Toast.makeText(MapActivity.this, "You selected " + title, Toast.LENGTH_SHORT).show();
// This triggers the update of the feature (Point) on the data source so it updates the SymbolLayer and you can see the feature enabled (bigger in this example)
geoJsonSource.setGeoJson(selectedFeature);
}
}
});
我找到的完整指南是这个https://blog.mapbox.com/a-guide-to-the-android-symbollayer-api-5daac7b66f2c非常棒,尽管一两个功能已被弃用,我寻找他们替代品。除此之外,这可能是深入了解 Mapbox SDK 的 SymbolLayer 的好方法。你可以用它做一些很好的事情。