How to display database values on mapbox? - javascript

I am using Mapbox and I created a database with values like (longitude and latitude), I want to display the data in the form of polygon on my map.
As you can see I want to put the the longitude and latitude from my database to the coordinates on my code but I don't know how to retrieve it from my database.
map.on('load', function() {
map.addSource('maine', {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[]
]
}
}
});
map.addLayer({
'id': 'maine',
'type': 'fill',
'source': 'maine',
'layout': {},
'paint': {
'fill-color': '#088',
'fill-opacity': 0.8
}
});
});
this is my database which is in the file api.php:

I don't know how to retrieve it from your database either, because you haven't provided any details. But generally speaking, your approach will be:
provide an API that provides access to the data in some form (such as CSV) via URL (example.com/mydatabase/points.csv)
fetch the CSV in the client, and transform it to GeoJSON. (If your back end can generate GeoJSON directly, you can save this step)
add it to the Mapbox map as a GeoJSON source layer

Related

Activate mapbox draw tool only within layer boundary

I have a geojson mapbox tileset visualized on a map. I am currently able to draw shapes such as polygons,polylines and add points to the map. But I now want to limit the draw tool to only allow drawing within the boundaries of the geojson layer. How would I do this? What I currently has, lets the cursor change to a pan symbol when it's outside of the map, and to a crosshair symbol when inside the map.
But once I click the draw tool buttons, it overrides this and lets the user draw anywhere they want.
mapboxgl.accessToken = config.MAPBOX_PUBLIC;
const map = new mapboxgl.Map({
attributionControl: false,
container: "map", // container ID
style: "mapbox://styles/mapbox/outdoors-v10",
center: [-69.45, 45.07], // starting position [lng, lat]
zoom: 8, // starting zoom
});
export function makeClickableArea() {
map.on("load", () => {
map.addSource('maine', {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
// These coordinates outline Maine.
'coordinates': [
[
[-67.13734, 45.13745],
[-66.96466, 44.8097],
[-68.03252, 44.3252],
[-69.06, 43.98],
[-70.11617, 43.68405],
[-70.64573, 43.09008],
[-70.75102, 43.08003],
[-70.79761, 43.21973],
[-70.98176, 43.36789],
[-70.94416, 43.46633],
[-71.08482, 45.30524],
[-70.66002, 45.46022],
[-70.30495, 45.91479],
[-70.00014, 46.69317],
[-69.23708, 47.44777],
[-68.90478, 47.18479],
[-68.2343, 47.35462],
[-67.79035, 47.06624],
[-67.79141, 45.70258],
[-67.13734, 45.13745]
]
]
}
}
});
// Add a new layer to visualize the polygon.
map.addLayer({
'id': 'maine',
'type': 'fill',
'source': 'maine', // reference the data source
'layout': {},
'paint': {
'fill-color': '#0080ff', // blue color fill
'fill-opacity': 0.5
}
});
// Add a black outline around the polygon.
map.addLayer({
'id': 'outline',
'type': 'line',
'source': 'maine',
'layout': {},
'paint': {
'line-color': '#000',
'line-width': 3
}
});
});
changeMouseSymbol();
}
// add the draw tool
function changeMouseSymbol() {
const modes = MapboxDraw.modes;
var draw = new MapboxDraw({
displayControlsDefault: false,
// Select which mapbox-gl-draw control buttons to add to the map.
controls: {
point: true,
line_string: true,
polygon: true,
},});
map.addControl(draw);
map.on("mouseover", "maine", () => {
map.getCanvas().style.cursor = "crosshair";
});
map.on("mouseleave", "maine", () => {
map.getCanvas().style.cursor = "";
});
}

How to get MapLibre Layers properties?

Please help, I have been suffering since 5 days.
How can I get all layer Idsof a MapLibre map ?
function addLayer(map, options, layer) {
let currentLayer = edges_data_api.find(
element => element.edge_id === layer.feature.properties.edge_id)
map.setPaintProperty('lines', 'fill-color', ['interpolate', ['linear'],
['get', currentLayer.lanes], 0, 'rgb(255, 255, 255)', 5, 'rgb(255, 0, 0)'])
}
Here is how I defined the map with MapLibre
map.on('load', function() {
map.addSource('lines', {
type: 'geojson',
data: data
});
map.addLayer({
'id': 'lines',
'type': 'fill',
'source': 'lines',
'layout': {},
'paint': {
'fill-color': '#4682B4',
'fill-opacity': 0.8,
}
});
map.setPaintProperty('lines', 'fill-color', ['get', 'color'])
})
As i know, there are no api for getAllLayers(). So u should keep list of layers' ids by you own.
//global variable
const layerIds = new Set()
map.on('load', function() {
layerIds.add('lines') //keep list of ids without duplicates
map.addSource('lines', {
type: 'geojson',
data: data
});
map.addLayer({
'id': 'lines',
'type': 'fill',
'source': 'lines',
'layout': {},
'paint': {
'fill-color': '#4682B4',
'fill-opacity': 0.8,
}
});
map.setPaintProperty('lines', 'fill-color', ['get', 'color'])
})
//You can iterate your list ids where it is needed
layerIds.forEach(value => {//action here})
From Style Specification
A style's layers property lists all the layers available in that style.
So you can get map's layers from the style object using Map.getStyle()
map.getStyle().layers
This returns an array containing the ids of all layers:
Object.keys( map.style._layers )
But beware: the code accesses private fields both of Map and Style, therefore it may, however unlikely, no longer work for new versions of MapLibre.

mapbox passing coordinates as variable does not work

It tried to implement the solution to draw a polygon from external data as shown in https://jsfiddle.net/zxaktouy/1/ but I get the error:
Input data given to 'frag15' is not a valid GeoJSON object.
My JS-method:
drawFragment : function(pFRAGMENT) {
const wPolygon = pFRAGMENT.coordinates;
console.log("drawFragment: Coords="+wPolygon);
wSourceId = "frag"+pFRAGMENT.id;
wFillId = "fragfill"+pFRAGMENT.id;
wOutlineId = "fragoutline"+pFRAGMENT.id;
map.addSource(wSourceId,{
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
wPolygon
]
}
}
});
// Add a new layer to visualize the polygon.
map.addLayer({
'id': wFillId,
'type': 'fill',
'source': wSourceId, // reference the data source
'layout': {},
'paint': {
'fill-color': '#00ff80', // green color fill
'fill-opacity': 0.5
}
});
// Add a black outline around the polygon.
map.addLayer({
'id': wOutlineId,
'type': 'line',
'source': wSourceId,
'layout': {},
'paint': {
'line-color': '#0d0',
'line-width': 2
}
});
},
And the data passed (perfectly shown via console.log) look like this:
[[8.543590974130666,47.377830192117756],
[8.543641551219707,47.37784384335191],
[8.543634914341965,47.37789513281288],
[8.543582309906242,47.37791046432616],
[8.543590974130666,47.377830192117756]]
when I replace the "wPolygon" just by copy-pasting the data into the code everything works fine.
After replacing:
const wPolygon = pFRAGMENT.coordinates;
with
var wPolygon = JSON.parse(pFRAGMENT.coordinates);
it works.

How to add Images inside a custom container on Mapbox?

I want to add images to Mapbox in a similar style as follow:
I am not sure how to go about doing this since Mapbox doesn't really offer many options when adding an image to the map. I have tried adding a custom marker with an image inside it and that works but then I lose layer features such as hiding etc. Any ideas on how this can be done?
You can load an image and then use it as part of a symbol layer. You can see it in one of the official examples.
map.on('load', function () {
map.loadImage(
'https://upload.wikimedia.org/wikipedia/commons/7/7c/201408_cat.png',
function (error, image) {
if (error) throw error;
map.addImage('cat', image);
map.addSource('point', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [0, 0]
}
}
]
}
});
map.addLayer({
'id': 'points',
'type': 'symbol',
'source': 'point',
'layout': {
'icon-image': 'cat',
'icon-size': 0.25
}
});
}
);
});

Show markers behind polygons

I have created circle (type polygon, with computed coordinates by this formula - still not sure if this is best way to render circle...)
and some markers, representing cities.
I prefer markers, because they are html elements and I can style them.
Circle serves as a radius for selecting cities.
My question is, how can I position these markers behind circle? Circle is part of canvas, and markers are separated divs, so there won't help any z-index.
Or should I create those markers somehow as points in canvas?
Looking exactly for this behaviour, only in mapboxgl.
Here is an example: https://jsfiddle.net/kmandov/vzc0o86g/
You can use turf-circle to create a circle using a specified radius and units. Turf-circle generates a geojson object that can be added to its own layer.
var center = {
"type": "Feature",
"properties": {
"marker-color": "#0f0"
},
"geometry": {
"type": "Point",
"coordinates": [-77.1117, 38.8739]
}
};
var lasso = turf.circle(center, 5, 20, 'kilometers');
Then you add it to its own layer. I've called it lasso:
map.addSource('lasso', {
'type': 'geojson',
'data': lasso
});
map.addLayer({
'id': 'lasso',
'type': 'fill',
'source': 'lasso',
'paint': {
'fill-color': '#f1f075',
'fill-opacity': 0.8
}
});
Then you add the layer containing the stations by specifying the layer above(example). This will make sure that the lasso layer is above the stations layer:
map.addLayer({
'id': 'stations',
'type': 'circle',
'source': 'stations',
'paint': {
'circle-color': '#feb24c',
'circle-opacity': 1,
'circle-radius': 5
}
}, 'lasso'); // lasso is the layer above

Categories