Skip to content

Instantly share code, notes, and snippets.

@robinvanemden
Last active September 12, 2016 15:46
Show Gist options
  • Save robinvanemden/8540765648ed2c8dc3d2aa8f742e71db to your computer and use it in GitHub Desktop.
Save robinvanemden/8540765648ed2c8dc3d2aa8f742e71db to your computer and use it in GitHub Desktop.
Querying Couchbase 4.1, Geospatial Views & GeoJSON in PHP
{
"type": "bird",
"name": "pooky",
"date": "09-04-16T16:09:42.918Z02:00",
"location": {
"type": "Point",
"coordinates": [
3.1,
5
]
}
}
// Design Doc to query: _design/bird [that is, $ddoc = "bird"]
// View name: bird_area
function (doc) {
if (doc.type == 'bird' && doc.location ) {
emit([doc.location], doc.name);
}
}
<?php
// Generate custom timestamp
$time = explode(" ",microtime());
$formated_date_time = date("m-d-y\TH:m:s",$time[1]).substr((string)$time[0],1,4)."Z".ltrim(date("P",$time[1]),"+");
// Connect to Couchbase Server
$cluster = new CouchbaseCluster("couchbase://127.0.0.1");
$bucket = $cluster->openBucket("default");
// Create GeoJSON point
$json = '{'
.'"type": "bird",'
.'"name": "pooky",'
.'"date": "'.$formated_date_time.'",'
.'"location": {'
.'"type": "Point",'
.'"coordinates": ['
.(rand(12, 57) / 10).','
.(rand(12, 57) / 10).''
.']'
.'}'
.'}';
// Upsert it into our bucket
$result = $bucket->upsert('bird_1', json_decode($json));
print("<br/>---------------------------------<br/>");
print_r($result);
print("<br/>---------------------------------<br/>");
// Query Spatial View
$query = CouchbaseViewQuery::fromSpatial("bird", "bird_area");
$birds = $bucket->query($query);
foreach ($birds->rows as $bird){
var_dump($bird);
}
print("<br/>---------------------------------<br/>");
// Print results
foreach ($birds->rows as $bird){
print_r($bird->geometry);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment