geofield.widgets.openlayers.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. /**
  3. * @file
  4. * Provides widget hooks on behalf of Openlayers.
  5. */
  6. /**
  7. * Implements hook_field_widget_info().
  8. */
  9. function openlayers_field_widget_info() {
  10. $widgets = array();
  11. $widgets['geofield_openlayers'] = array(
  12. 'label' => t('Openlayers Map'),
  13. 'field types' => array('geofield'),
  14. 'behaviors' => array(
  15. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  16. ),
  17. );
  18. return $widgets;
  19. }
  20. /**
  21. * Implements hook_field_widget_settings_form().
  22. */
  23. function openlayers_field_widget_settings_form($field, $instance) {
  24. $widget = $instance['widget'];
  25. $settings = $widget['settings'];
  26. $form = array();
  27. // Get preset options, filtered to those which have the GeoField behavior and *don't* have the draw features behavior, which is incompatible
  28. $maps = openlayers_maps();
  29. $map_options = array();
  30. foreach ($maps as $map) {
  31. if (array_key_exists('openlayers_behavior_geofield', $map->data['behaviors']) && !array_key_exists('openlayers_behavior_drawfeatures', $map->data['behaviors'])) {
  32. $map_options[$map->name] = $map->title;
  33. }
  34. }
  35. if (empty($map_options)) {
  36. form_set_error('openlayers_map', "Error: You have no compatible openlayers maps. Make sure that at least one preset has the 'GeoField' behavior enabled and that it does not have the 'Draw Features' behavior enabled (which is incompatible).");
  37. }
  38. $form['openlayers_map'] = array(
  39. '#type' => 'select',
  40. '#title' => t('OpenLayers Map'),
  41. '#default_value' => isset($settings['openlayers_map']) ? $settings['openlayers_map'] : 'geofield_widget_map',
  42. '#options' => $map_options,
  43. '#description' => t('Select which OpenLayers map you would like to use. Only maps which have the GeoField behavior may be selected. If your preferred map is not here, add the GeoField behavior to it first. The "Draw Features" bahavior is incompatible - presets with this behavior are not shown.'),
  44. );
  45. $form['data_storage'] = array(
  46. '#type' => 'radios',
  47. '#title' => t('Storage Options'),
  48. '#description' => t('Should the widget only allow simple features (points, lines, or polygons), or should the widget allow for complex features? Note that changing this setting from complex to simple after data has been entered can lead to data loss.'),
  49. '#options' => array(
  50. 'single' => 'Store each simple feature as a separate field.',
  51. 'collection' => 'Store as a single collection.',
  52. ),
  53. '#default_value' => (isset($settings['data_storage'])) ? $settings['data_storage'] : 'single',
  54. );
  55. $form['feature_types'] = array(
  56. '#title' => t('Available Features'),
  57. '#type' => 'checkboxes',
  58. '#options' => array(
  59. 'point' => t('Point'),
  60. 'path' => t('Path'),
  61. 'polygon' => t('Polygon'),
  62. ),
  63. '#description' => t('Select what features are available to draw.'),
  64. '#default_value' => isset($settings['feature_types']) ? $settings['feature_types'] : array('point' => 'point', 'path' => 'path', 'polygon' => 'polygon'),
  65. );
  66. $form['allow_edit'] = array(
  67. '#title' => t('Allow shape modification'),
  68. '#type' => 'checkbox',
  69. '#description' => t('Can you edit and delete shapes.'),
  70. '#default_value' => isset($settings['allow_edit']) ? $settings['allow_edit'] : 1,
  71. );
  72. // Add optional Geocoder support.
  73. $use_geocoder = isset($settings['use_geocoder']) ? $settings['use_geocoder'] : 0;
  74. $geocoder_form = array(
  75. '#type' => 'fieldset',
  76. '#title' => t('Geocoder settings'),
  77. );
  78. if (module_exists('geocoder')) {
  79. $geocoder_form['use_geocoder'] = array(
  80. '#type' => 'checkbox',
  81. '#title' => t('Enable geocoding of location data'),
  82. '#default_value' => $use_geocoder,
  83. // Can't nest this in a fieldset element without affecting data storage so instead hardcode one.
  84. '#prefix' => '<fieldset><legend><span="fieldset-legend">' . t('Geocoder settings') . '</span></legend><div class="fieldset-wrapper">',
  85. );
  86. // Load the Geocoder widget settings.
  87. module_load_include('inc', 'geocoder', 'geocoder.widget');
  88. $new = geocoder_field_widget_settings_form($field, $instance);
  89. // Show the geocoder fields only if geocoder is selected.
  90. openlayers_widget_add_states($new, ':input[name="instance[widget][settings][use_geocoder]"]');
  91. // Close the fieldset we opened in the #prefix to use_geocoder.
  92. $element_children = element_children($new);
  93. $new[end($element_children)]['#suffix'] = '</div></fieldset>';
  94. $geocoder_form += $new;
  95. }
  96. else {
  97. $geocoder_form['add_geocoder'] = array(
  98. '#markup' => t('Optionally, install the <a href="http//drupal.org/project/geocoder">Geocoder</a> module and add an <a href="http://drupal.org/project/addressfield">Address field</a> to enable mapping by address.')
  99. );
  100. }
  101. $form += $geocoder_form;
  102. return $form;
  103. }
  104. /**
  105. * Recurse through form elements adding a visibility #states selector
  106. * and removing #required flags.
  107. */
  108. function openlayers_widget_add_states(&$element, $selector) {
  109. foreach (element_children($element) as $key) {
  110. $element[$key]['#required'] = FALSE;
  111. // Don't override any existing #states settings.
  112. if (!isset($element[$key]['#states'])) {
  113. $element[$key]['#states'] = array();
  114. }
  115. if (!isset($element[$key]['#states']['visible'])) {
  116. $element[$key]['#states']['visible'] = array();
  117. }
  118. $element[$key]['#states']['visible'][$selector] = array('checked' => TRUE);
  119. openlayers_widget_add_states($element[$key], $selector);
  120. }
  121. }
  122. /**
  123. * Implements hook_field_widget_form().
  124. */
  125. function openlayers_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  126. geophp_load();
  127. $widget = $instance['widget'];
  128. $parents = $form['#parents'];
  129. $field_name = $field['field_name'];
  130. $id_prefix = implode('-', array_merge($parents, array($field_name, $delta)));
  131. $wrapper_id = drupal_html_id($id_prefix . '-use-geocoder-wrapper');
  132. $settings_defaults = array(
  133. 'openlayers_map' => 'geofield_widget_map',
  134. 'data_storage' => 'single',
  135. 'feature_types' => array(
  136. 'point' => 'point',
  137. 'path' => 'path',
  138. 'polygon' => 'polygon',
  139. ),
  140. 'allow_edit' => 1,
  141. );
  142. $settings = array_merge($settings_defaults, $widget['settings']);
  143. // Compress all the WKT elements into a single WKT object to pass to the map.
  144. // Essentially we compress all the elements into delta 0, then deconstruct them on the other side when it comes time to validate them
  145. $geoms = array();
  146. foreach ($items as $delta => $item) {
  147. if (is_array($item) && array_key_exists('geom', $item)) {
  148. $geoms[] = geoPHP::load($item['geom']);
  149. }
  150. else {
  151. $geoms[] = geoPHP::load($item);
  152. }
  153. }
  154. $combined_geom = geoPHP::geometryReduce($geoms);
  155. if ($combined_geom) {
  156. // We want to force the combined_geom into a geometryCollection
  157. $geom_type = $combined_geom->geometryType();
  158. if ($geom_type == 'MultiPolygon' || $geom_type == 'MultiLineString' || $geom_type == 'MultiPoint') {
  159. $combined_geom = new GeometryCollection($combined_geom->getComponents());
  160. }
  161. $combined_wkt = $combined_geom->out('wkt');
  162. // A value of 'GEOMETRYCOLLECTION EMPTY' breaks OpenLayers JS later on down the line.
  163. if ($combined_wkt == 'GEOMETRYCOLLECTION EMPTY') {
  164. $combined_wkt = '';
  165. }
  166. }
  167. else {
  168. $combined_wkt = '';
  169. }
  170. $element['geom'] = array(
  171. '#type' => 'hidden',
  172. '#attributes' => array('class' => array('geofield_wkt')),
  173. '#default_value' => $combined_wkt,
  174. '#required' => (isset($instance['required'])) ? $instance['required'] : FALSE,
  175. );
  176. $element['input_format']['#value'] = GEOFIELD_INPUT_WKT;
  177. $openlayers_map_id = !empty($instance['widget']['settings']['openlayers_map']) ? $instance['widget']['settings']['openlayers_map'] : 'geofield_widget_map';
  178. $element['#openlayers_mapname'] = $openlayers_map_id;
  179. $element['#after_build']= array('openlayers_geofield_widget_afterbuild');
  180. $element['#data_storage'] = (!empty($settings['data_storage'])) ? $settings['data_storage'] : 'collection';
  181. // Attach the widget and field settings so they can be accesses by JS and validate functions
  182. $element['#widget_settings'] = $settings;
  183. $element['#widget_settings']['allow_edit'] = (bool) $settings['allow_edit'];
  184. $element['#widget_settings']['feature_types'] = array();
  185. foreach ($settings['feature_types'] as $feature => $feature_setting) {
  186. if ($feature_setting) {
  187. $element['#widget_settings']['feature_types'][] = $feature;
  188. }
  189. }
  190. $element['#widget_settings']['cardinality'] = $field['cardinality'];
  191. // Make sure we set the input-format to WKT so geofield knows how to process it
  192. $element['input_format'] = array(
  193. '#type' => 'value',
  194. '#value' => GEOFIELD_INPUT_WKT,
  195. );
  196. // Time to deal with optional geocoder integration
  197. // Conditionally add geocoder button.
  198. $is_settings_form = isset($form['#title']) && $form['#title'] == t('Default value');
  199. if (!$is_settings_form && !empty($settings['use_geocoder']) && !empty($settings['geocoder_field'])) {
  200. if ($field = field_info_instance($instance['entity_type'], $settings['geocoder_field'], $instance['bundle'])) {
  201. $label = $field['label'];
  202. }
  203. else {
  204. switch ($settings['geocoder_field']) {
  205. case 'title':
  206. $label = t('Title');
  207. break;
  208. case 'name':
  209. $label = t('Name');
  210. break;
  211. default:
  212. $label = $settings['geocoder_field'];
  213. }
  214. }
  215. $element['#prefix'] = '<div id="' . $wrapper_id . '">';
  216. $element['#suffix'] = '</div>';
  217. $element['use_geocoder'] = array(
  218. '#type' => 'submit',
  219. '#name' => strtr($id_prefix, '-', '_') . '_use_geocoder',
  220. '#value' => t('Find using @field field', array('@field' => $label)),
  221. '#attributes' => array('class' => array('field-use-geocoder-submit')),
  222. // Avoid validation errors for e.g. required fields but do pass the value of the geocoder field.
  223. '#limit_validation_errors' => array(array_merge($parents, array($field_name, $langcode)), array($settings['geocoder_field'], $langcode)),
  224. '#ajax' => array(
  225. 'callback' => 'openlayers_widget_geocode',
  226. 'wrapper' => $wrapper_id,
  227. 'effect' => 'fade',
  228. ),
  229. '#submit' => array('openlayers_use_geocoder_submit'),
  230. );
  231. }
  232. // Add the element to an array, because it's the format that FIELD_BEHAVIOR_CUSTOM expects
  233. $full_element = array($element);
  234. // Override the element_validate as we need to deal with deltas
  235. unset($full_element[0]['#element_validate']);
  236. $full_element['#element_validate'][] = 'openlayers_geofield_widget_element_validate';
  237. return $full_element;
  238. }
  239. /**
  240. * Callback for afterbuild for widget for js addition to
  241. */
  242. function openlayers_geofield_widget_afterbuild($element, &$form_state) {
  243. $defaults = array();
  244. $element['geofield_openlayers_map'] = array(
  245. '#markup' => '<div class="form-item geofield-openlayers-map" style="display:block">'
  246. . openlayers_geofield_form_latlon_map(array(), $element['#openlayers_mapname'])
  247. . '</div>');
  248. $element['geofield_openlayers_map_desc'] = array(
  249. '#markup' => t('<div class="description geofield-help">Use the icons to select what type of feature to draw. Each map can contain one simple feature. Pan and zoom with arrows and the zoom bar.</div>')
  250. );
  251. drupal_add_js(
  252. array(
  253. 'geofield' => array(
  254. 'widget_settings' => $element['#widget_settings'],
  255. ),
  256. ),
  257. 'setting'
  258. );
  259. return $element;
  260. }
  261. /**
  262. * Create LatLon Helper Map.
  263. */
  264. function openlayers_geofield_form_latlon_map($defaults = array(), $map_name) {
  265. // Pass variables etc. to javascript
  266. // Set up our map to help set lat and lon
  267. // This map will always be projected as 4326 and use just the default map preset
  268. $map_data = openlayers_map_load($map_name);
  269. $map = $map_data->data;
  270. return openlayers_render_map($map);
  271. }
  272. /**
  273. * Submit callback for widget form.
  274. */
  275. function openlayers_use_geocoder_submit($form, &$form_state) {
  276. $button = $form_state['triggering_element'];
  277. // Go one level up in the form, to the widgets container.
  278. $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  279. $field_name = $element['#field_name'];
  280. $langcode = $element['#language'];
  281. $delta = $element['#delta'];
  282. $parents = $element['#field_parents'];
  283. // Set the widget value based on geocoding results.
  284. $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  285. $geocoder_field = $field_state['instance']['widget']['settings']['geocoder_field'];
  286. if ($field_value = geocoder_widget_get_field_value($element['#entity_type'], $field_state['instance'], NULL, $form_state['values'][$geocoder_field][$langcode])) {
  287. geophp_load();
  288. $geometry = geoPHP::load($field_value[$langcode][$delta]['geom']);
  289. $field_value[$langcode][$delta]['geom'] = $geometry->out('wkt'); // OpenLayers can only use WKT, so translate
  290. $field_value[$langcode][$delta]['input_format'] = 'wkt';
  291. // Override the field's value in the 'input' array to substitute the new
  292. // field value for the one that was submitted.
  293. drupal_array_set_nested_value($form_state, array_merge(array('values'), $parents, array($field_name)), $field_value);
  294. }
  295. }
  296. /**
  297. * Return the altered form element from an AJAX request.
  298. *
  299. * @see openlayers_field_widget_form()
  300. */
  301. function openlayers_widget_geocode($form, $form_state) {
  302. $button = $form_state['triggering_element'];
  303. // Go one level up in the form, to the widgets container.
  304. $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  305. $field_name = $element['#field_name'];
  306. $langcode = $element['#language'];
  307. $delta = $element['#delta'];
  308. $parents = $element['#field_parents'];
  309. $value = drupal_array_get_nested_value($form_state, array_merge(array('values'), $parents, array($field_name)));
  310. $element['geom']['#value'] = $value[$langcode][$delta]['geom'];
  311. // Return the map, but remove the '_weight' element inserted
  312. // by the field API.
  313. unset($element['_weight']);
  314. return $element;
  315. }
  316. function openlayers_geofield_widget_element_validate($element, &$form_state) {
  317. $container_delta = $element[0];
  318. if (!empty($container_delta['geom']['#value'])) {
  319. geophp_load();
  320. $combined_geom = geoPHP::load($container_delta['geom']['#value']);
  321. $combined_geom = geoPHP::geometryReduce($combined_geom);
  322. // Check to make sure they only saved the allowed types
  323. $geom_type = $combined_geom->geometryType();
  324. if ($geom_type == 'GeometryCollection' || $geom_type == 'MultiPoint' || $geom_type == 'MultiLineString' || $geom_type == 'MultiPolygon') {
  325. $geoms = $combined_geom->getComponents();
  326. }
  327. else {
  328. $geoms = array($combined_geom);
  329. }
  330. foreach ($geoms as $item) {
  331. $allowed = FALSE;
  332. foreach ($container_delta['#widget_settings']['feature_types'] as $type) {
  333. $geometry_type = strtolower($item->geometryType());
  334. if ($geometry_type == 'linestring') {
  335. $geometry_type = 'path';
  336. }
  337. if (strpos(strtolower($geometry_type), $type) !== FALSE) {
  338. $allowed = TRUE;
  339. break;
  340. }
  341. }
  342. if (!$allowed) {
  343. form_set_error($container_delta['#field_name'], 'Not allowed to submit a geometry of type ' . $item->geometryType());
  344. return;
  345. }
  346. }
  347. //Check the number deltas
  348. $cardinality = $container_delta['#widget_settings']['cardinality'];
  349. if ($cardinality > 0 && $container_delta['#widget_settings']['data_storage'] == 'single') {
  350. if (count($geoms) > $cardinality) {
  351. form_set_error($container_delta['#field_name'], 'Too many geometries submitted. Max allowed is ' .$cardinality);
  352. return;
  353. }
  354. }
  355. // Checks pass, lets load this up into deltas
  356. if ($container_delta['#widget_settings']['data_storage'] == 'collection') {
  357. //Assign values to the form state
  358. form_set_value($element[0]['geom'], $combined_geom->out('wkt'), $form_state);
  359. }
  360. if ($container_delta['#widget_settings']['data_storage'] == 'single') {
  361. foreach ($geoms as $delta => $geom) {
  362. // Clone delta-0
  363. $element = $container_delta;
  364. // Override the delta
  365. openlayers_geofield_override_element_delta($element, 0, $delta);
  366. // Assign the value in the form_state
  367. form_set_value($element['geom'], $geom->out('wkt'), $form_state);
  368. }
  369. }
  370. }
  371. }
  372. function openlayers_geofield_override_element_delta(&$element, $source_delta, $delta) {
  373. if (isset($element['#parents'])) {
  374. foreach ($element['#parents'] as $index => $item) {
  375. if (is_numeric($item) && $item == $source_delta) {
  376. $element['#parents'][$index] = $delta;
  377. }
  378. }
  379. }
  380. if (isset($element['#array_parents'])) {
  381. foreach ($element['#array_parents'] as $index => $item) {
  382. if ($item == $source_delta) {
  383. $element['#array_parents'][$index] = $delta;
  384. }
  385. }
  386. }
  387. foreach ($element as $key => &$item) {
  388. if (substr($key, 0,1) != '#') {
  389. openlayers_geofield_override_element_delta($item, $source_delta, $delta);
  390. }
  391. }
  392. }