1

I am using the Geolocation module and I have created a custom content type (we'll call it Bookshop), which contains a field called location and is of type Geolocation.

I can already programmatically create the custom content type instance and programmatically populate the title field.

    $node=Node::create(
      'title'=>'Shop 1'
    );

    $node->save();

How would I go about populating the the Geolocation field content (e.g. the longitude and latitude fields in the Geolocation field)? e.g.

    $node=Node::create(
      'title'=>'Shop 1'
      'Geolocation field'=>array ('latitude'=>'1', 'longitude'=>'2.33'),
    );

An approach such as the one above does not appear to work?

2 Answers 2

6

Pretty straight forward just had to change the field names to correspond with the field names used by Geolocation:

$node=Node::create(
  'type' => 'content type - machine name',
  'title' => 'Shop 1',
  'geolocation_field' => ['lat'=> 1, 'lng' => 2.33]
);
$node->save();
0
<?php
use Drupal\node\Entity\Node;

$node = Node::load($nid);
//set value for body field
$node->body->value = 'body';
$node->body->format = 'full_html';

//save value for geolocation field.
//field_geolocation will be your field machine name
$node->field_geolocation = ['lat'=> 12, 'lng' => 2.33];
//save to update node
$node->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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