I am trying to fetch a comma separated list of coordinates from a database and then show them on a Mapbox GL JS map.
By using the following FeatureCollection, I am able to show a Line between coordinates:
const route = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': [
[0.05505231549481921,50.795082814869524], [0.054870226332090315,50.79614745729873]
]
}
}
]
};
This simply draws a line between the two coordinates shown. However using a PHP script to fetch from a MySQL database a string of coordinates, I cannot get the line to show.
<?php
$array["routeCoords"] = $pointArray; // [0.05505231549481921,50.795082814869524], [0.054870226332090315,50.79614745729873]
return json_encode($array);
The problem I am facing is that the Mapbox FeatureCollection doesn't recognise the coordinates in the same way as if they were printed within the block itself.
URL of Output:
{"routeCoords":"[0.05505231549481921,50.795082814869524],[0.054870226332090315,50.79614745729873]"}
Jquery code to handle and display the coordinates:
const payload = await fetch(URL); //Url returns JSON data above.
const data = await payload.json();
let coords = [];
$.each(data.routeCoords, function(index, value){
coords.push(value);
});
coords = JSON.stringify(coords);
const route = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': [
coords
]
}
}
]
};
Just getting started but the core of my product will store the LineString coordinates in a database and return them depending on a route, so it is dynamic. There will be other (non geographical) data returned in the same JSON payload so the above is simply cut down.
Hopefully an obvious mistake.
coords = JSON.stringify(coords)- why? In the first code, you passed an array of arrays forcoordinates- now you are passing a string value.coord must be GeoJSON Point or an Array of numberswhen I pass an array to the coordinates. For example now I have an array and each of the [Long, Lat] formatted Coordinates as individual values in the array, and trying to use that array variable in the Feature code throws that error, despite it being an array of Lon/Lat coords.