phpdrupalcoordinatesgeospatialdrupal-8

Save geofield programmatically in Drupal 8


I have read in a lot of sources that I should use the geofield_compute_values() function when trying to programmatically save coordinates in Drupal.

However it does not work for me, that function is undefined in the Drupal 8.5.2 that I am using.

I've installed geofield using composer and I can use it as usual in the admin area and there are no problems with saving there.

Here are some examples I've tried with, the first example gives me undefined function geofield_compute_values() :

$geofield_data = geofield_compute_values([
    'lat' => $lat,
    'lon' => $lon,
], GEOFIELD_INPUT_LAT_LON);

$cbisProduct->set('field_koordinater', $geofield_data);

I have also tried this out with no successful result and no errors :

$geofield = [
    'geom' => "POINT (" . $lon . " " . $lat . ")",
    'geo_type' => 'point',
    'lat' => $lat,
    'lon' => $lon,
    'left' => $lon,
    'top' => $lat,
    'right' => $lon,
    'bottom' => $lat,
];

$cbisProduct->set('field_koordinater', $geofield);

Solution

  • Seems like you're trying to use the geofield_compute_values() function which was available in 7.x version, but not in 8.x

    You should look into the wkt_generator service. i.e.

    <?php $wktGenerator = \Drupal::service('geofield.wkt_generator'); ?>
    

    I haven't tried this, but something like this should work:

    <?php
    
    $point = [
      'lat' => $request->get('lat'), 
      'lon' => $request->get('lon'),
    ];
    $value = \Drupal::service('geofield.wkt_generator')->WktBuildPoint($point);
    
    $node->field_koordinater->setValue($value);
    

    Also, WktGeneratorTest.php and GeofieldItemTest.php files could be a good start to see how to use the service in your implementation.