After a user adds markers to the Google Map, I store the data as a JSON string in my MySQL database. The latitude and longitude of each marker are represented by "k" and "D," respectively:
[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]
Additionally, I save the polylines connecting the markers in this format:
[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]
To retrieve all the markers and polylines from the database for display, I use the following query:
function getMarkersByTripId($tripId)
{
if ($bdd = mysqli_connect(_BDD_HOST_, _BDD_USERNAME_, _BDD_PASSWORD_, _BDD_NAME_)) {
$sql = 'SELECT DISTINCT `markers`, `polylines` FROM `trip` WHERE `trip_id` = "'.$tripId.'"';
$req = mysqli_query($bdd, $sql);
if ($req) {
while ($row = mysqli_fetch_row($req)) {
$jsonData= array('markers'=>$row[0], 'polylines'=>$row[1]);
}
echo json_encode($jsonData);
}
else {
echo json_encode(array('status' => 'failure'));
}
}
if ($bdd) {
mysqli_close($bdd);
}
}
A var_dump of $jsonData reveals the structure as follows:
array(2) {
["markers"]=>
string(79) "[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]"
["polylines"]=>
string(63) "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"
}
In my JavaScript code, when I log the jsonText variable, it is formatted like this:
"{"markers":"[{\"k\":52.908902047770255,\"D\":-3.427734375},{\"k\":56.31653672211301,\"D\":7.03125}]","polylines":"[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"}"
I then attempt to convert this JSON string into an object using JSON.parse() method:
var jsonData = JSON.parse(jsonText);
console.log(jsonData);
The parsing seems successful with the output resembling:
Object { markers: "[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]", polylines: "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]" }
However, the issue arises when trying to access the latitude/longitude values ("k"/"D" elements) after parsing the JSON data:
console.log(jsonData['markers'].k);
This always returns "undefined," preventing me from adding the marker to the map. I suspect that the JSON parsing may be affected by double quotes added during retrieval from the MySQL database. Any guidance on resolving this would be greatly appreciated.