Remove Lines from MapboxGL map - reactjs

I have a React function like the following. When a button is clicked, this function places a square on a map of the world at the specified coordinates (see code). However, I want to be able to press a different button and have the square removed. How can I do this? Is there a way to delete things from MapboxGL maps? If so, what function can I use?
The square is rendered using a function from MapboxGL and the web app is made using React JS.
React.useEffect(() => {
if(props.show) {
console.log(props);
var northEast = [131.308594, 46.195042];
var southEast = [117.597656, 8.233237];
var southWest = [79.101563, 32.842674];
var northWest = [86.847656, 44.715514];
// Add bounding box to the map
// Defines bounding box
globalMap.addSource('newroute', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'LineString',
'coordinates': [
northEast, southEast, southWest, northWest, northEast
]
}
}
});
// Draws bounding box
globalMap.addLayer({
'id': 'newroute',
'type': 'line',
'source': 'newroute',
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': '#ff0000',
'line-width': 5
}
});
}
});

Mapbox-GL has a remove layer method.
// If a layer with ID 'target-layer' exists, remove it.
if (map.getLayer('target-layer')) map.removeLayer('target-layer');
Another way to approach the issue is to keep the old layer, and update the data of the source with the new data (if your use-case allows for it).
"Remove layer" by setting the data of the source to an empty dataset:
map.getSource('target-source').setData({ type: "FeatureCollection", features: [] });
You can then set the data to a populated GeoJSON object if and when you have new data...

Related

Display HTML clusters with custom properties using react-map-gl (Mapbox)

I am trying to adapt the example Display HTML clusters with custom properties for react-map-gl.
I got basic clusters without custom styling working (adapted from Create and style clusters):
<ReactMapGL ref={mapRef}>
<Source id="poi-modal-geojson" type="geojson" data={pointsToGeoJSONFeatureCollection(points)}
cluster={true}
clusterMaxZoom={14}
clusterRadius={50}
>
<Layer {...{
id: 'clusters',
type: 'circle',
source: 'poi-modal-geojson',
filter: ['has', 'point_count'],
paint: {
'circle-color': [
'step',
['get', 'point_count'],
'#51bbd6',
100,
'#f1f075',
750,
'#f28cb1'
],
'circle-radius': [
'step',
['get', 'point_count'],
20,
100,
30,
750,
40
]
}
}} />
<Layer {...{
id: 'unclustered-point',
type: 'circle',
source: 'poi-modal-geojson',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': '#11b4da',
'circle-radius': 4,
'circle-stroke-width': 1,
'circle-stroke-color': '#fff'
}
}} />
</Source>
</ReactMapGL>
Here, pointsToGeoJSONFeatureCollection(points: any[]): GeoJSON.FeatureCollection<GeoJSON.Geometry> is a function returning a GeoJSON (adapted from here).
However, I need more complex styling of markers and I am trying to adapt Display HTML clusters with custom properties without success so far. I mainly tried to adapt updateMarkers() and to call it inside useEffect():
const mapRef: React.Ref<MapRef> = React.createRef();
const markers: any = {};
let markersOnScreen: any = {};
useEffect(() => {
const map = mapRef.current.getMap();
function updateMarkers() {
const newMarkers: any = {};
const features = map.querySourceFeatures('poi-modal-geojson');
// for every cluster on the screen, create an HTML marker for it (if we didn't yet),
// and add it to the map if it's not there already
for (const feature of features) {
const coords = feature.geometry.coordinates;
const props = feature.properties;
if (!props.cluster) continue;
const id = props.cluster_id;
let marker = markers[id];
if (!marker) {
let markerProps = {
key: 'marker' + id,
longitude: coords[0],
latitude: coords[1],
className: 'mapboxgl-marker-start'
}
const el = React.createElement(Marker, markerProps, null),
marker = markers[id] = el;
}
newMarkers[id] = marker;
if (!markersOnScreen[id]) {
// TODO re-add
// marker.addTo(map);
}
}
// for every marker we've added previously, remove those that are no longer visible
for (const id in markersOnScreen) {
if (!newMarkers[id]) delete markersOnScreen[id];
}
markersOnScreen = newMarkers;
}
// after the GeoJSON data is loaded, update markers on the screen on every frame
map.on('render', () => {
if (!map.isSourceLoaded('poi-modal-geojson')) return;
updateMarkers();
});
}, [points]);
Unfortunately, the Marker created using React.createElement() isn't displayed I am not sure what is the right approach to create Marker elements in updateMarkers() or if my approach is completely wrong.
There is a great article on marker clustering which uses the supercluster and use-supercluster libraries and it makes clustering really easy not only for map box but for other map libraries as well, you can find it here.
You just have to convert your points into GeoJSON Feature objects in order to pass them to the useSupercluster hook and for the calculations to work. It will return an array of points and clusters depending on your current viewport, and you can map through it and display the elements accordingly based on the element.properties.cluster flag.
The properties property of the GeoJSON Feature object can be custom so you can pass whatever you need to display the markers later on when you get the final cluster array.

Connect markers with a polyline in Mapbox GL

I'm developing a web application using Mapbox GL, more specifically, its binding for React, react-map-gl.
One of the planned functionalities for the app is adding markers and connecting them.
However, I'm having trouble connecting markers.
I want to start drawing the line when I click on a marker, add a breakpoint to the line when I click elsewhere and finish the line when I click on another marker.
What can I use for this?
I am also working on same, you can use deck.gl for plotting lines on map, or you can also use geoJson for the same.
What I ended up doing was using an EditableGeoJsonLayer with the features for both the markers and the connections between them as follows:
data: {
type: "FeatureCollection",
features: markers.flatMap((marker) => {
// Map markers
let features = [
{
geometry: {
type: "Point",
coordinates: marker.coordinates
},
type: "Feature",
node: marker
}
];
// Map connections
if (marker.connections.length > 0) {
features = features.concat(
marker.connections.flatMap((endMarker) => [
{
geometry: {
type: "LineString",
coordinates: [
marker.coordinates,
endMarker.coordinates
]
},
type: "Feature"
}
])
);
}
return features;
})
}

Mapbox layer not updating after source update

I'm using Redux state to update an array of coordinates in a Mapbox source. I initially check if there is a source with the id, if yes, I set the data of the source, if not I add the source to the map. When the redux state is changed, it triggers an effect which updates the coordinates of the features in the geojson object and uses setData to change the source. I've tried removing the layer, changing source and adding the layer, which just gave me the old layer (even though the source had indeed been updated). I also tried just updating the source alone and seeing if the layer would update dynamically, it did not.
Here is the code for the effect, which is triggered when the redux state is changed.
useEffect(() => {
const geoJsonObj = {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: []
}
};
for (let i = 0; i < (props.mapRoutes.length); i++) {
geoJsonObj.data.features.push({
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: props.mapRoutes[i].geometry.coordinates
}
});
};
const routeLayer = {
id: 'route',
type: 'line',
source: 'route',
layout: {
'line-join': 'round',
'line-cap': 'round'
},
paint: {
'line-color': '#ff3814',
'line-width': 5,
'line-opacity': 0.75
}
};
const jsonString = JSON.stringify(geoJsonObj);
const jsonObj = JSON.parse(jsonString);
if (props.mapRoutes.length) {
if (map.current.getSource('route')) {
map.current.getSource('route').setData(jsonObj);
} else {
map.current.addSource('route', jsonObj);
map.current.addLayer(routeLayer);
};
};
}, [props.mapRoutes]);
Neither of these worked and I am having trouble finding how to update a layer based on an updated source. Everything seems right when I inspect the source in the console, I just can't manage to update the layer on the map.
Any help would be appreciated.
I found the problem, I was using the original geoJson object for the setData method instead of the data entry, which was one level too high in the object. Just a simple error which was overlooked.

How to pass an array of coordinates to react-map-gl heatmap layer?

having some trouble reconciling the docs to my use-case. I got a little stuck trying to get openstreet maps into react using d3, and have been playing around with react-map-gl...great library that's pretty dialed-in! This library is built on top of d3 and openstreetmaps and uses a lot of d3 plugins...here's the example I am trying to replicate:
https://github.com/uber/react-map-gl/blob/5.0-release/examples/heatmap/src/app.js
In this example, the data where the coordinates live is in a geoJson file, and it is accessed in a method that looks like this (Copied and pasted from the link above...in this code they are using the d3-request plugin to fetch and parse through the geoJson file, which contains other data about earthquakes etc):
_handleMapLoaded = event => {
const map = this._getMap();
requestJson(
'https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson',
(error, response) => {
if (!error) {
// Note: In a real application you would do a validation of JSON data before doing anything with it,
// but for demonstration purposes we ingore this part here and just trying to select needed data...
const features = response.features;
const endTime = features[0].properties.time;
const startTime = features[features.length - 1].properties.time;
this.setState({
earthquakes: response,
endTime,
startTime,
selectedTime: endTime
});
map.addSource(HEATMAP_SOURCE_ID, {type: 'geojson', data: response});
map.addLayer(this._mkHeatmapLayer('heatmap-layer', HEATMAP_SOURCE_ID));
}
}
);
};
This is great if you are using GeoJson, and I have done this quite a bit to point d3 towards an object for US states, counties, or zipcodes...However what I am trying to do is much simpler! I have an array of data that I'm fetching, and passing down as props to this heatmap component, and it looks something like this:
[
{name: locationOne, latitude: 1.12345, longitude: -3.4567},
{name: locationTwo, latitude: 1.2345, longitude: -5.678},
...etc
]
So the question is, if I am not using geoJson, how do I tell the heatmap what coordinates to use? Any help is appreciated!!!
Even though the data in your array isn't geoJson, we can manipulate it into geoJSON. We can do this by creating a factory function to return valid geoJSON using the array data.
Once the data is converted to geoJSON it can be used as shown in the example you've found.
const rawData = [
{name: 'Feature 1', value: 2, latitude: 1.12345, longitude: -3.4567},
{name: 'Feature 2', value: 5, latitude: 1.2345, longitude: -5.678},
];
const makeGeoJSON = (data) => {
return {
type: 'FeatureCollection',
features: data.map(feature => {
return {
"type": "Feature",
"properties": {
"id": feature.name,
"value": feature.value
},
"geometry": {
"type": "Point",
"coordinates": [ feature.latitude, feature.longitude]
}
}
})
}
};
const myGeoJSONData = makeGeoJSON(rawData);
console.log(myGeoJSONData);

Export GPX file from Leaflet

What I want to do is let the users create a GPX file by selecting some GeoJson features in Leaflet. The way in which I'm doing it is by creating a new GeoJson layer to store the selected features, then converting this to gpx with a plugin called togpx (https://github.com/tyrasd/togpx). Now I have a gpx file, but I don't know how can I let the users download it. Any suggestions? Here's my code:
var GPXfile;
var trails = new L.GeoJSON.AJAX('data/trasee.geojson', {
onEachFeature: function(feature, layer) {
layer.on({
click: function () {
var selectedGeojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Rocka Rolla"
},
"geometry": {
"type": "LineString",
"coordinates": feature.geometry.coordinates
}
}]
}
GPXfile = togpx(selectedGeojson);
}
})
}
}).addTo(map);
A JsFiddle might help: http://jsfiddle.net/pufanalexandru/20ara4qe/1/
You can try that ...
A link to trigger the dowload:
Export to file
Some javascript (you have to include jquery):
$("#exportGPX").on('click', function (event) {
// prepare the string that is going to go into the href attribute
// data:mimetype;encoding,string
data = 'data:application/javascript;charset=utf-8,' + encodeURIComponent(gpxData);
// set attributes href and target in the <a> element (with id exportGPX)
$(this).attr({
'href': data,
'target': '_blank'
});
// let the click go through
});
An example here: http://jsfiddle.net/FranceImage/vxe23py4/
Note: it works with Chrome, but you should try other browsers too.

Resources