Skip to content

Instantly share code, notes, and snippets.

@wboykinm
Last active September 13, 2024 19:00
Show Gist options
  • Save wboykinm/5730504 to your computer and use it in GitHub Desktop.
Save wboykinm/5730504 to your computer and use it in GitHub Desktop.
Sample PHP to Point GeoJSON
<?php
/**
* PHP GeoJSON Constructor, adpated from https://github.com/bmcbride/PHP-Database-GeoJSON
*/
# Connect to MySQL database
$conn = new PDO('mysql:host=localhost;dbname=mydatabase','myusername','mypassword');
# However the User's Query will be passed to the DB:
$sql = 'SELECT * from GDA_database WHERE user_query = whatever';
# Try query or error
$rs = $conn->query($sql);
if (!$rs) {
echo 'An SQL error occured.\n';
exit;
}
# Build GeoJSON feature collection array
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
# Loop through rows to build feature arrays
while($row = mysql_fetch_assoc($dbquery)) {
$feature = array(
'id' => $row['partnership_id'],
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
# Pass Longitude and Latitude Columns here
'coordinates' => array($row['longitude'], $row['latitude'])
),
# Pass other attribute columns here
'properties' => array(
'name' => $row['Name'],
'description' => $row['Description'],
'sector' => $row['Sector'],
'country' => $row['Country'],
'status' => $row['Status'],
'start_date' => $row['Start Date'],
'end_date' => $row['End Date'],
'total_invest' => $row['Total Lifetime Investment'],
'usg_invest' => $row['USG Investment'],
'non_usg_invest' => $row['Non-USG Investment']
)
);
# Add feature arrays to feature collection array
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment