Last active
September 7, 2022 20:03
-
-
Save mstenta/c1393a79776c7a7feb2ff8e650e34216 to your computer and use it in GitHub Desktop.
Fix farmOS v1 geometry longitudes per https://github.com/farmOS/farmOS/issues/33
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Load GeoPHP. | |
geophp_load(); | |
// Function for recursively fixing the longitude points within a Geometry. | |
function recursive_fix_lon(&$feature) { | |
$fixed = FALSE; | |
if ($feature->geometryType() == 'Point' && !empty($feature->coords[0])) { | |
$lon = &$feature->coords[0]; | |
$lon = fmod($lon, 360); | |
if ($lon < -180) { | |
$lon += 360; | |
$fixed = TRUE; | |
} | |
elseif ($lon > 180) { | |
$lon -= 360; | |
$fixed = TRUE; | |
} | |
} | |
elseif ($feature->geometryType() != 'Point' && !empty($feature->components)) { | |
foreach ($feature->components as $component) { | |
if (recursive_fix_lon($component)) { | |
$fixed = TRUE; | |
} | |
} | |
} | |
return $fixed; | |
} | |
// Load a list of entities with a non-empty geometry field. | |
$query = new EntityFieldQuery(); | |
$query->fieldCondition('field_farm_geofield', 'geom', '', '!=')->addMetaData('account', user_load(1)); | |
$result = $query->execute(); | |
// Iterate through the list. | |
$fixed_entities = 0; | |
foreach ($result as $entity_type => $data) { | |
$entity_ids = array_keys($data); | |
foreach ($entity_ids as $entity_id) { | |
// Load the entity. | |
$load = entity_load($entity_type, array($entity_id)); | |
$entity = reset ($load); | |
// Iterate through the geometries. | |
if (!empty($entity->field_farm_geofield[LANGUAGE_NONE])) { | |
foreach ($entity->field_farm_geofield[LANGUAGE_NONE] as &$value) { | |
if (!empty($value['geom'])) { | |
// Load the geometry. | |
$features = geoPHP::load($value['geom'], 'wkt'); | |
// Fix the longitude points. | |
$fixed = recursive_fix_lon($features); | |
// If points were fixed, save it. | |
if ($fixed) { | |
$features->setGeos(NULL); | |
$value = geofield_get_values_from_geometry($features); | |
entity_save($entity_type, $entity); | |
$fixed_entities++; | |
} | |
} | |
} | |
} | |
} | |
} | |
drupal_set_message('Fixed ' . $fixed_entities . ' entitites'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you need a version of this for farmOS v2, see: https://gist.github.com/mstenta/fbc912cb0e41f6af4f32b22b742009c7