Skip to content

Instantly share code, notes, and snippets.

@chriscalip
Created July 15, 2015 02:10
Show Gist options
  • Save chriscalip/62ec7310bcd9c5eac172 to your computer and use it in GitHub Desktop.
Save chriscalip/62ec7310bcd9c5eac172 to your computer and use it in GitHub Desktop.
Utility drupal php function to get polygon data from node containing a geofield that stores polygons.
<?
/**
* Utility function to get market areas map data.
* Pretty much just a typical parse entities data into market areas array
*
* @param array $filters contextual array (entity_type, bundle, field_name)
* @return array $market_areas output array used for painting market area layer.
*/
function capacitype_mapbox_get_market_areas($filters) {
$market_areas = array();
// if any of the expected filters are not provided , exit.
if ( empty($filters['entity_type']) ||
empty($filters['bundle']) ||
empty($filters['field_name']) ||
($filters['entity_type'] != 'node')
) {
return array();
}
$query = new EntityFieldQueryExtraFields();
$query->entityCondition('entity_type', $filters['entity_type'])
->propertyCondition('type', $filters['bundle'])
// adds node title.
->addTag('ctm_mapbox_specific');
//->propertyCondition('status', 1);
$results = $query->execute();
if (!isset($results['node'])) {
return array();
}
$display_fields = array($filters['field_name']);
$fields = field_info_instances($filters['entity_type'], $filters['bundle']);
if (empty($fields)) {
return array();
}
// pretty expensive operation.. try to find a better way..
// $nodes = node_load_multiple(array_keys($results['node']));
// better than node_load_multiple because of less hook_node_load calls.
// depending on cache situation results might have other fields also included from cache data
// but this makes sure we have all fields data as specified in display fields.
foreach ($display_fields as $display_field) {
if (isset($fields[$display_field]['field_id'])) {
field_attach_load($filters['entity_type'],
$results['node'],
FIELD_LOAD_CURRENT,
array('field_id' => $fields[$display_field]['field_id'])
);
}
}
geophp_load();
foreach ($results['node'] as $nid => $node) {
$feature = $properties = array();
if (!isset($node->{$filters['field_name']}[LANGUAGE_NONE][0])) {
continue;
}
$item = $node->{$filters['field_name']}[LANGUAGE_NONE][0];
$geometry = geoPHP::load($item['geom']);
if ($geometry->isEmpty()) {
continue;
}
$geojson = $geometry->out('json');
$properties['nid'] = $nid;
// include the title coming from previous efq query.
$properties['title'] = $node->extraFields->title;
if (isset($node->title)) {
$properties['name'] = $node->title;
}
$data = array('geometry' => $geojson);
if (!empty($properties)) {
$data['properties'] = $properties;
}
$market_areas[] = $data;
}
return $market_areas;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment