I’ve been fighting this forever I’m trying to figure out how to display google map markers from an object array generated in php, which I have JSON encoded and can access in my js file. Specifically I’m unsure how to either format my data so that the google maps marker parameters accept it, or how to define the parameters within the marker code.
Here are the important bits from the different programs:
PHP
$query = "SELECT LATITUDE as LAT, LONGITUDE as LNG, BUSINESSNAME as SHOP
FROM mechanic
WHERE LATITUDE <> ''
AND LATITUDE IS NOT NULL
";
if ($result = $conn -> query($query)) {
while ($obj = $result -> fetch_object()) {
// save the results to an object array on each iteration
$objects[] = $obj;
}
$result -> free_result();
}
?>
<script>var locations = <?php echo json_encode($objects); ?>
ARRAY IN JS
console.log(locations);
Array(3) [ {…}, {…}, {…} ]
0: Object { LAT: "38.6152529", LNG: "-90.3559897", SHOP: "Toms Auto Care" }
1: Object { LAT: "26.0039884", LNG: "-80.1416624", SHOP: "Sams Shop" }
2: Object { LAT: "38.6152529", LNG: "-90.3559896", SHOP: "Mels Shop" }
length: 3
GOOGLE MAP MARKER code sample in js that I am completely lost on getting to use the array:
locatons.forEach(([position, title], i) => {
const marker = new google.maps.Marker({
position,
map,
title: `${i + 1}. ${title}`,
label: `${i + 1}`,
optimized: false,
});
I’ve been trying this for a long time, in many formats, I’m unsure if I had to make it into an object array, but I finally got that together, and now I have no idea how to get the markers constructor to use the lat lng and shop name.
2
Answers
This is all the changes to the above that were needed to make it work:
Your PHP is fine and the json_encode is the right way, but there is a small change needed in the JavaScript.
This should do the trick:
You loop through the locations with forEach and get a single location and use that object for the new marker.