Displaying GeoJSON Points, Lines, and Polygons
🎯 Introduction
By the end of this article, you will be able to convert API data to GeoJSON, display locations, routes, and areas, and replace the data dynamically.
🧱 Describe application features with GeoJSON
GeoJSON stores spatial shapes in geometry objects and application fields such as names and status in properties. Points represent locations, lines represent paths, and polygons represent enclosed areas.
const geojson = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
id: 'station-1',
properties: { name: 'Station A', status: 'online' },
geometry: {
type: 'Point',
coordinates: [116.397, 39.909],
},
},
],
}
id provides a stable identity for a feature, which highlighting, selection, and incremental state updates depend on. Use an application primary key that remains unchanged; do not generate random IDs after each request.
📍 Display points, lines, and polygons separately
map.addSource('business-data', {
type: 'geojson',
data: geojson,
})
map.addLayer({
id: 'business-points',
type: 'circle',
source: 'business-data',
filter: ['==', ['geometry-type'], 'Point'],
paint: { 'circle-radius': 7, 'circle-color': '#16a34a' },
})
map.addLayer({
id: 'business-lines',
type: 'line',
source: 'business-data',
filter: ['==', ['geometry-type'], 'LineString'],
paint: { 'line-width': 4, 'line-color': '#f97316' },
})
map.addLayer({
id: 'business-polygons',
type: 'fill',
source: 'business-data',
filter: ['==', ['geometry-type'], 'Polygon'],
paint: { 'fill-color': '#8b5cf6', 'fill-opacity': 0.25 },
})
A source containing mixed geometry types can feed different layers through geometry-type filters. For polygon outlines, add a line layer using the same source and filter.
The following example displays points, lines, and polygons from one GeoJSON dataset:
🔄 Update data with setData
const source = map.getSource('business-data') as mapboxgl.GeoJSONSource
source.setData(nextGeoJSON)
setData replaces the source data and automatically redraws existing layers without removing or recreating them. Reuse sources for frequent updates to avoid repeatedly creating map resources and event listeners.
Click “Update with setData” below. Location A moves and Location C is added, while the circle and text layers remain the same instances throughout.
🔧 Convert API data to GeoJSON
const featureCollection = {
type: 'FeatureCollection',
features: rows
.filter(row => Number.isFinite(row.longitude) && Number.isFinite(row.latitude))
.map(row => ({
type: 'Feature',
id: row.id,
properties: {
name: row.name,
status: row.status,
},
geometry: {
type: 'Point',
coordinates: [row.longitude, row.latitude],
},
})),
}
Validate that coordinates are numbers, longitude and latitude are in the correct order, and geometry rings are closed where required. Each Polygon ring must start and end with the same coordinate. An empty FeatureCollection can represent an empty application layer; there is no need to invent a placeholder feature.
⚠️ Common errors
- Reversed coordinates: features appear in the wrong region or fail to display.
- A
LineStringwith fewer than two coordinates: invalid geometry. - An unclosed Polygon ring: incorrect fills or rejected data.
- A geometry type that does not match the layer type: data exists but is invisible.
- Fields outside the geometry but not inside
properties: expressions and click handlers cannot read them.
🧾 Summary
- GeoJSON stores shapes in geometry objects and application fields in
properties. - Circle, line, and fill layers display points, lines, and polygons, respectively.
- Stable feature IDs are essential for selection and highlighting.
- The same polygon data can render both fills and outlines.
- Prefer
setDatafor updates instead of recreating sources and layers. - Validate coordinates, geometry, and empty datasets when converting API data.
❓ Questions and answers
Q1: Can properties contain nested objects?
GeoJSON can carry JSON data, but Mapbox expressions work best with flat string, number, and boolean fields. Keep complex objects in application state and look them up by ID.
Q2: Why does highlighting disappear after a data update?
Without stable IDs in the new data, existing feature state cannot be matched to the new features.
Q3: Should I remove a layer when there is no data?
Usually not. Set an empty FeatureCollection on the source to preserve the layer configuration.
🧪 Exercises
- Convert three plain objects to Point features, preserving
nameandstatus. - Move one point to new coordinates with
setData.
// Write your code here
🎉 You now know how to display GeoJSON points, lines, and polygons!
