3

I need to write a lat/lon value to a Geofield and I can't figure out how to set the field. I would prefer to do this using EntityMetadataWrapper.

5

And the answer:

    $entity_metadata_wrapper = entity_metadata_wrapper('node', $node_object);

    $data = array(
       'lat' => 44,
       'lon' => -93
    );

    $entity_metadata_wrapper->field_position->set($data);
| improve this answer | |
  • 1
    Although this is the accepted answer, I think 42droids ltd is the better one. – Cameron Mar 4 '17 at 13:23
4

Set Geofield using EntityMetadataWrapper if you only have the Longitude & Latitude information. (2015):

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

  $entity_metadata_wrapper->field_position->set($geofield_data);

When a geofield is saved using the provided widgets, these values are passed through the geofield_compute_values function in order to compute dependent values. By default dependent values are computed based on WKT, but this may be overriden to compute values based on other columns. For example, geofield_compute_values may be called like so:

geofield_compute_values($values, GEOFIELD_INPUT_LAT_LON);

This will compute the wkt field (and all other fields) based on the lat/lon columns, resulting in a point. As a developer this is important to remember if you modify geofield information using node_load and node_save. Make sure to run any modified geofield instances through geofield_compute_values in order to make all columns consistent.

See docs (bottom) for more details: http://cgit.drupalcode.org/geofield/plain/README.txt?id=7.x-1.x

| improve this answer | |
1

This can be done without entity_metadata_wrapper() as:

$node_object->position[LANGUAGE_NONE][0] = array(
  'input_format' => GEOFIELD_INPUT_LAT_LON,
  'geom' => array('lat' => 44, 'lon' => -93),
);

(I know you said "preferably with EntityMetadataWrapper", but I just thought I'd throw this in for reference.)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.