I am wanting to index a mysql result set to use outside of the while loop.
I have a simplistic script set up that runs the standard while loop on the result set. That works fine.
I want to get at each row of specific columns in order to put that data into an indexed array, for example
$lat['lat'][0], $lng['lng'][0]
That way I can index through the results outside the loop. In particular, to be used for mapping coordinates.
So, I have a sql table named address with columns named latitude and longitude which contain respective coordinates.
I have this code which will echo out each row inside the loop
Thanks, I think that should work really nicely. However, I’m not able to get the markers to show. It seems my PHP version is to low to use mysqli_fetch_all. I’ve adapted the code and except for the markers not showing up, it is working.
You don’t need to assign the return value to an array as fetchAll already returns an array. Unfortunately, the rowCount function doesn’t work with SELECT queries, so you have to count the results some other way, but fortunately fetchAll will just return an empty array if no results were found, which is easy to check for.
You’re still looping over the markers in PHP, which is no longer necessary as we’re doing the looping in JS. Try this:
(function () {
var coords = <?php echo json_encode($data); ?>,
options = {
zoom: 11,
center: new google.maps.LatLng(coords[0]['latitude'], coords[0]['longitude']),
mapTypeId: 'roadmap'
},
map = new google.maps.Map(document.getElementById('map-canvas'), options);
for (var i = 0; i < coords.length; i++) {
var latLng = new google.maps.LatLng(coords[i].latitude, coords[i].longitude),
marker = new google.maps.Marker({
position: latLng,
map: map
});
places.push(latLng);
}
})();
Note that you don’t actually need to wrap your JS in a window.onload function. Just place the script block right before the closing </body> tag and the JS will only run once the page has loaded.
Ahhh, that works beautifully and is succinctly coded to boot. I’m very appreciative of the tips -thank you. Oh, and obviously I meant to say liking json_encode.
For others that may look at this, please note to declare the places var before the for loop.
Thanks again fretburner!