I am trying to output a JSON string using PHP and MySQL but the latitude and longitude is outputting as a string with quotes around the values. This causes an issue when I am trying to add the markers to a google map.
Here is my code:
$sql = mysql_query('SELECT * FROM markers WHERE address !=""');
$results = array();
while($row = mysql_fetch_array($sql))
{
$results[] = array(
'latitude' =>$row['lat'],
'longitude' => $row['lng'],
'address' => $row['address'],
'project_ID' => $row['project_ID'],
'marker_id' => $row['marker_id']
);
}
$json = json_encode($results);
echo "{\"markers\":";
echo $json;
echo "}";
Here is the expected output:
{"markers":[{"latitude":0.000000,"longitude":0.000000,"address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]}
Here is the output that I am getting:
{"markers":[{"latitude":"0.000000","longitude":"0.000000","address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]}
Notice the quotes around the latitude and longitude values.
My Answer:
(string)$row['latitude'],
'longitude' => (string)$row['longitude'],
'name' => $row['name'],
'address' => $row['address']
);
}
echo json_encode($results);
This code will typecast the latitude and longitude values to strings before adding them to the results array. When you encode the results array to JSON, the latitude and longitude values will not have quotes around them.
Rate this post
5 of 5 based on 2923 votesComments