I query the latitud and longitud from my database and stored these values in php using arrays. Since I have to use javaScript to use the Google API I pass the arrays to javaScript arrays but when I tried to make an addMarker function to pass the latitude and longitude, the marker is not being displayed.
If there is a problem using the Json way to pass an php array i would ,ike to know too.
var lat = "[{"latitude":"-73.44282246117739"},{"latitude":"-73.43353928556874"},{"latitude":"-74.01881776353744"},{"latitude":"-74.0188170929852"}]"; var lng = "[{"longitude":"40.73354088144067"},{"longitude":"40.76232657450102"},{"longitude":"40.64831233555079"},{"longitude":"40.648312844313715"}]"; var name = "[{"name":"Saint Kilian"},{"name":"Island Harvest"},{"name":"Long Island Cares Inc"},{"name":"City Harvest"}]"; var urls = "[{"url":"https://stkilian.com/"},{"url":"https://www.islandharvest.org/"},{"url":"https://www.licares.org/"},{"url":"http://www.cityharvest.org/"}]"; var map;
`
This is the javascript Code
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
width: 600px;
height: 400px;
margin-left: 50%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var lat = <?php echo json_encode($latitudes); ?>;
var lng = <?php echo json_encode($longitudes); ?>;
var name = <?php echo json_encode($names); ?>;
var urls = <?php echo json_encode($urls); ?>;
var map;
var latLong = {};
lat.forEach((element, index) => {
latLong[element] = lng[index];
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: {lat: 40.75296142342573 , lng: -73.42661893505269},
});
addMarker(latLong);
function addMarker(){
console.log(myLatlng);
var markerMap= new google.maps.Marker({
position: {myLatlng[0]},
map,
});
const popUp = "Hi";
//Info Windows
const detailWindow = new google.maps.InfoWindow({
content: popUp,
ariaLabel: "Food Bank",
});
markerMap.addListener("click", ()=>{
detailWindow.open({
anchor: markerMap,
map,
});
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api /js?key=API_KEY&callback=initMap"
async defer></script>
</body>
</html>
`
For some reason only works with a static latitude and longitude.
2
Answers
I solved it, I was using associative fetch in PHP, and my arrays became objects instead of arrays. after I fetched by rows and used parseFloat when accessing the data in JavaScript, I was able to get the markers to show.
This might helps.
Remember json_encode() parameter must be array or object.
Use single quotes or double quotes to enclose json data in javascript.