Visualizing data

Contents

Typically the Maps SDK will be used to visualize data on top of the map. Data could vary from simple dots-on-a-map to more complex pieces like 3D buildings, route paths, geofences, and more.

The recommended way to visualize custom data on top of the map is through the use of Sources and Layers.

Sources store the data you want to visualize. Layers, depending on the type set, will visualize that data on the map.

  • Sources and Layers are attached to the map’s style. Therefore if you change styles after setting those sources and layers, you will need to re-apply them.

  • Sources and Layers should not be added to a style until the onStyleLoaded() callback is fired.

Sources

Sources store and contain the data you wish to visualize on the map. A Layer will reference a source by its id, and pull from the source for rendering purposes. The two required parameters for a source are a unique String id and the type of data being stored. There are a variety of source types such as vector and raster, but the most commonly used is the GeoJson type. A simple GeoJsonSource example:

map.setStyle(Style.MOBILE_DAY, new Style.OnStyleLoaded() {
   @Override
   public void onStyleLoaded(@NonNull Style style) {
       Point myFirstPoint = Point.fromLngLat(-74.59938481233185, 40.36121994571363);
       Point mySecondPoint = Point.fromLngLat(-74.59962554057138, 40.36102527529048);

       Feature myFirstFeature = Feature.fromGeometry(myFirstPoint);
       Feature mySecondFeature = Feature.fromGeometry(mySecondPoint);

       FeatureCollection myFeatureCollection = FeatureCollection.fromFeatures(new Feature[]{myFirstFeature, mySecondFeature});

       GeoJsonSource myNewSource = new GeoJsonSource("myGreatSource", myFeatureCollection);

       style.addSource(myNewSource);

   }
});

In the example above, once the onStyleLoaded() callback is fired, two GeoJson points / features are created. They are added to a FeatureCollection which is then assigned to the source. Finally, the source is added to the style.

Using JSON / URI in a source

While you can create Features manually as shown above, a URI can also be used as the data for a source. The Source will pull the data from that URI location, negating the need to manually create a FeatureCollection yourself. See below:

map.setStyle(Style.MOBILE_DAY, new Style.OnStyleLoaded() {
    @Override
    public void onStyleLoaded(@NonNull Style style) {
        try {
            URI locationOfData = new URI("https://my-geojson-data.geojson");
            GeoJsonSource myNewSource = new GeoJsonSource("myGreatSource", locationOfData);

            style.addSource(myNewSource);

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }
});

The above will use the data the URI points to, and that will become the geojson data used by the source.

Last updated September 22, 2021.