I am trying to add a marker to my gmaps.js map. The long. and lat. values are stored in a database, which I select using a PHP Script.
Once fetched, both of the long. and lat. values are stored in an array, under the variable $data.
I wanted to use json_encode($data); in order to pass the variables, however I would have had to change the header to a json application, I have already echoed some PHP onto the page, therefore this is unfeasable.
I have now tried echoing the json_encode into the jQuery function using an $.each loop, however it has been unsuccessful, as not every entry retrieved by the database will have a marker.
What is the best solution, to get an ID, long. and lat. value for max 10 records, pass this to a jQuery function to position on a map?
As not all records have markers, youll have to parse the results so that only the required data gets passed to your js function. I'd create a php array and add the marker I'd, lat,long etc... Under the same key:
$markersarray = array ()
foreach($records as $record){
if($record['lat'] != ““){
$markersarray[] = array(
'id'=>$record['id'],
'lat'=>$record['lat'],
'long'=>$record['long']
);
}
}
$markersjson = json_encode($markersarray);
Then you could use a hidden input to store the encoded json string which then could be passed into your js.
<input id="markersjson" type="hidden" value="<?php echo $markersjson; ?>"/>
in your js function
var markersdata = $('#markersjson').val();
You may need to parse this value to an object
var obj = jQuery.parseJSON(markersdata);
then use a $.each to loop through your obj