> This is the Markdown version of the page. For the complete Lattice Developers documentation index, fetch https://developer.anduril.com/llms.txt. Append .md to any page URL for its clean Markdown.

# Draw geo shapes

> Publish points, lines, polygons, and ellipses as geo-entities on the map

A *geo-entity* is a shape, region, or point of interest drawn on the map, which may not physically exist.
Use geo-entities to represent geographical areas of interest, such as an airfield, or a control zone
for autonomous vehicles to operate in.

This page shows how to publish a polygon that defines a control area, and how to model the other
shapes that Lattice supports: points, lines, and ellipses.

## Before you begin

* To publish geo-entities, [set up the Lattice SDK](/guides/getting-started/set-up) and set up a Lattice environment.
* Learn about the required components and [entity templates](/guides/entities/overview#entity-templates) in Lattice.

> **gRPC authentication**
>
> These gRPC examples authenticate with a static environment token attached as request metadata.
> If you are using OAuth 2.0 client credentials instead, [set up the token refresh module](/guides/getting-started/authenticate#client-credentials) before running the examples on this page.

## Geo-entity components

In addition to the [required components](/guides/entities/overview#entity-model), a geo-entity uses
the following components:

**`ontology.template`** `Template` — required

Set [`template`](/reference/rest/entities/publish-entity#request.body.ontology.template)
to `TEMPLATE_GEO` to render the entity as a shape on the map.

---

**`geo_details`** `GeoDetails` — required

Set the [`geo_details`](/reference/rest/entities/publish-entity#request.body.geoDetails) type, such as
`GEO_TYPE_GENERAL` for a general shape or `GEO_TYPE_CONTROL_AREA` for a zone that
constrains autonomous vehicles.

---

**`geo_shape`** `GeoShape` — required

Define the shape itself in [`geo_shape`](/reference/rest/entities/publish-entity#request.body.geoShape):
a `point`, `line`, `polygon`, or `ellipse`.

---

**`location`** `Location`

Set the center of the shape in [`location`](/reference/rest/entities/publish-entity#request.body.location)
when `geo_shape` is an [ellipse](/reference/rest/entities/publish-entity#request.body.geoShape.ellipse).
Other shapes carry their positions in `geo_shape`.

---

## Publish a polygon

A polygon is the most common geo shape. It outlines an area, such as an airfield or a zone that
autonomous vehicles must stay in or avoid. To publish a polygon that defines a loiter zone, do the
following:

#### Define the entity

Define the entity model's required components. Together with the geo-entity-specific
components, you get the following entity object:

**`entity_model.json`**

```json maxLines=25 title="entity_model.json"
{
  "entityId": "UNIQUE_ENTITY_ID",
  "description": "Polygon entity",
  "isLive": true,
  "createdTime": "2025-05-28T18:16:34.969Z",
  "noExpiry": true,
  "aliases": {
    "name": "Control-Area 1"
  },
  "ontology": {
    "template": "TEMPLATE_GEO"
  },
  "geoDetails": {
    "type": "GEO_TYPE_CONTROL_AREA",
    "controlArea": {
      "type": "CONTROL_AREA_TYPE_LOITER_ZONE"
    }
  },
  "geoShape": {
    "polygon": {
      "rings": [
        {
          "positions": [
            {
              "position": {
                "latitudeDegrees": 33.641132,
                "longitudeDegrees": -117.918669,
                "altitudeAglMeters": 500
              },
              "heightM": 1
            },
            {
              "position": {
                "latitudeDegrees": 33.646911,
                "longitudeDegrees": -117.929123,
                "altitudeAglMeters": 500
              },
              "heightM": 1
            },
            {
              "position": {
                "latitudeDegrees": 33.635059,
                "longitudeDegrees": -117.917482,
                "altitudeAglMeters": 500
              },
              "heightM": 1
            },
            {
              "position": {
                "latitudeDegrees": 33.641132,
                "longitudeDegrees": -117.918669,
                "altitudeAglMeters": 500
              },
              "heightM": 1
            }
          ]
        }
      ]
    }
  },
  "provenance": {
    "integrationName": "your_integration_name",
    "dataType": "test_data",
    "sourceUpdateTime": "2025-05-28T18:17:34.866Z"
  }
}
```

#### Define the shape

Take a closer look at the following components in `entity_model.json`. You define `rings` to
create the polygon. Each ring must have *at least four* points, each represented by a
`position` component.

> **Info**
>
> The last point of a ring must be the same as its first point, which closes the shape.

**`ontology`**

```json title="ontology"
"ontology": {
  // Set the required template.
  "template": "TEMPLATE_GEO"
}
```

**`geoDetails`**

```json title="geoDetails"
"geoDetails": {
  // Set the type of the geo-entity to GEO_TYPE_CONTROL_AREA.
  // This type is commonly used to represent special zones for
  // autonomous entities to operate in.
  "type": "GEO_TYPE_CONTROL_AREA",
  "controlArea": {
    "type": "CONTROL_AREA_TYPE_LOITER_ZONE"
  }
}
```

**`geoShape`**

```json title="geoShape"
"geoShape": {
  "polygon": {
    "rings": [
      {
        "positions": [
          {
            "position": {
              "latitudeDegrees": 33.641132,
              "longitudeDegrees": -117.918669,
              "altitudeAglMeters": 500
            },
            "heightM": 1
          },
          {
            "position": {
              "latitudeDegrees": 33.646911,
              "longitudeDegrees": -117.929123,
              "altitudeAglMeters": 500
            },
            "heightM": 1
          },
          {
            "position": {
              "latitudeDegrees": 33.635059,
              "longitudeDegrees": -117.917482,
              "altitudeAglMeters": 500
            },
            "heightM": 1
          },
          {
            "position": {
              "latitudeDegrees": 33.641132,
              "longitudeDegrees": -117.918669,
              "altitudeAglMeters": 500
            },
            "heightM": 1
          }
        ]
      }
    ]
  }
}
```

Each point in the polygon has a minimum altitude defined as `altitudeAglMeters`.
The `heightM` component sets the additional height, in meters, above `altitudeAglMeters`.

This example defines a three-sided polygon that represents a loiter zone. Other control area
types include `CONTROL_AREA_TYPE_KEEP_IN_ZONE` and `CONTROL_AREA_TYPE_KEEP_OUT_ZONE`.

#### Publish the entity

Use the [`PublishEntity`](/reference/rest/entities/publish-entity) API method to publish the entity:

```go title={"Go (REST)"} startLine={93} maxLines={46}
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"time"

	Lattice "github.com/anduril/lattice-sdk-go/v5"
	"github.com/anduril/lattice-sdk-go/v5/client"
	"github.com/anduril/lattice-sdk-go/v5/option"
	"github.com/google/uuid"
)

func main() {
	// Get environment variables
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")

	// Remove sandboxesToken from the following statements if you are not developing on Sandboxes
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	// Check required environment variables
	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		fmt.Println("Missing required environment variables")
		os.Exit(1)
	}

	// Initialize headers for sandbox authorization
	headers := http.Header{}
	headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))

	// Create the client
	LatticeClient := client.NewClient(
		option.WithToken(environmentToken),
		option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
		option.WithHTTPHeader(headers),
	)

	// Generate a unique ID for the entity
	entityId := uuid.New().String()

	// Get creation time
	creationTime := time.Now().UTC()

	// Entities must be republished at least every 5 minutes to persist across Lattice service restarts
	for {
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Create positions for the polygon
		positions := []*Lattice.GeoPolygonPosition{
			// First point
			{
				Position: &Lattice.Position{
					LatitudeDegrees:   Lattice.Float64(33.641132),
					LongitudeDegrees:  Lattice.Float64(-117.918669),
					AltitudeAglMeters: Lattice.Float64(500),
				},
				HeightM: Lattice.Float64(1),
			},
			// Second point
			{
				Position: &Lattice.Position{
					LatitudeDegrees:   Lattice.Float64(33.646911),
					LongitudeDegrees:  Lattice.Float64(-117.929123),
					AltitudeAglMeters: Lattice.Float64(500),
				},
				HeightM: Lattice.Float64(1),
			},
			// Third point
			{
				Position: &Lattice.Position{
					LatitudeDegrees:   Lattice.Float64(33.635059),
					LongitudeDegrees:  Lattice.Float64(-117.917482),
					AltitudeAglMeters: Lattice.Float64(500),
				},
				HeightM: Lattice.Float64(1),
			},
			// Fourth point (same as first to close the polygon)
			{
				Position: &Lattice.Position{
					LatitudeDegrees:   Lattice.Float64(33.641132),
					LongitudeDegrees:  Lattice.Float64(-117.918669),
					AltitudeAglMeters: Lattice.Float64(500),
				},
				HeightM: Lattice.Float64(1),
			},
		}

		// Create entity to publish
		entity := Lattice.Entity{
			EntityID:    &entityId,
			Description: Lattice.String("Polygon entity"),
			Aliases: &Lattice.Aliases{
				Name: Lattice.String("Control-Area Loiter Zone"),
			},
			IsLive:      Lattice.Bool(true),
			CreatedTime: Lattice.Time(creationTime),
			NoExpiry:    Lattice.Bool(true),
			Ontology: &Lattice.Ontology{
				Template: Lattice.OntologyTemplateTemplateGeo.Ptr(),
			},
			GeoDetails: &Lattice.GeoDetails{
				Type: Lattice.GeoDetailsTypeGeoTypeControlArea.Ptr(),
				ControlArea: &Lattice.ControlAreaDetails{
					Type: Lattice.ControlAreaDetailsTypeControlAreaTypeLoiterZone.Ptr(),
				},
			},
			GeoShape: &Lattice.GeoShape{
				Polygon: &Lattice.GeoPolygon{
					Rings: []*Lattice.LinearRing{
						{
							Positions: positions,
						},
					},
				},
			},
			Provenance: &Lattice.Provenance{
				IntegrationName:  Lattice.String("your_integration_name"),
				DataType:         Lattice.String("test_data"),
				SourceUpdateTime: Lattice.Time(latestTimestamp),
			},
		}

		// Publish the entity
		_, err := LatticeClient.Entities.PublishEntity(ctx, &entity)

		// Handle errors
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Println("Publishing geo entity")
		}

		// Republishing every 10 seconds
		time.Sleep(10 * time.Second)
	}
}

```

```java title={"Java (REST)"} startLine={140} maxLines={31}
package org.example;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import com.anduril.Lattice;
import com.anduril.types.Aliases;
import com.anduril.types.ControlAreaDetails;
import com.anduril.types.ControlAreaDetailsType;
import com.anduril.types.Entity;
import com.anduril.types.GeoDetails;
import com.anduril.types.GeoDetailsType;
import com.anduril.types.GeoPolygon;
import com.anduril.types.GeoPolygonPosition;
import com.anduril.types.GeoShape;
import com.anduril.types.LinearRing;
import com.anduril.types.Ontology;
import com.anduril.types.OntologyTemplate;
import com.anduril.types.Position;
import com.anduril.types.Provenance;



public class PublishGeoEntityPolygon {
    public static void main(String[] args) {
        // Get environment variables
        String endpoint = System.getenv("LATTICE_ENDPOINT");
        String environmentToken = System.getenv("ENVIRONMENT_TOKEN");
        String sandboxesToken = System.getenv("SANDBOXES_TOKEN");
        
        // Check required variables and ensure URL has https://
        if (endpoint == null || environmentToken == null || sandboxesToken == null) {
            System.err.println("Missing required environment variables");
            System.exit(1);
        }
        if (!endpoint.startsWith("https://")) endpoint = "https://" + endpoint;
        
        try {
            // Create Lattice client with Sandbox authentication
            Lattice client = Lattice.builder()
                .url(endpoint)
                .token(environmentToken)
                .addHeader("Anduril-Sandbox-Authorization", "Bearer " + sandboxesToken)
                .build();
            
            // Generate a unique ID for the entity
            String entityId = UUID.randomUUID().toString();
            
            // Get creation time
            Instant creationTime = Instant.now();
            
            // Entities must be republished at least every 5 minutes to persist across Lattice service restarts
            while (true) {
                try {
                    // Get current timestamp
                    Instant latestTimestamp = Instant.now();
                    
                    // Create positions for the polygon
                    List<GeoPolygonPosition> positions = new ArrayList<>();
                    
                    // First point
                    Position pos1 = Position.builder()
                        .latitudeDegrees(33.641132)
                        .longitudeDegrees(-117.918669)
                        .altitudeAglMeters(500.0)
                        .build();
                    
                    GeoPolygonPosition geoPos1 = GeoPolygonPosition.builder()
                        .position(pos1)
                        .heightM(1.0f)
                        .build();
                    positions.add(geoPos1);
                    
                    // Second point
                    Position pos2 = Position.builder()
                        .latitudeDegrees(33.646911)
                        .longitudeDegrees(-117.929123)
                        .altitudeAglMeters(500.0)
                        .build();
                    
                    GeoPolygonPosition geoPos2 = GeoPolygonPosition.builder()
                        .position(pos2)
                        .heightM(1.0f)
                        .build();
                    positions.add(geoPos2);
                    
                    // Third point
                    Position pos3 = Position.builder()
                        .latitudeDegrees(33.635059)
                        .longitudeDegrees(-117.917482)
                        .altitudeAglMeters(500.0)
                        .build();
                    
                    GeoPolygonPosition geoPos3 = GeoPolygonPosition.builder()
                        .position(pos3)
                        .heightM(1.0f)
                        .build();
                    positions.add(geoPos3);
                    
                    // Fourth point (same as first to close the polygon)
                    Position pos4 = Position.builder()
                        .latitudeDegrees(33.641132)
                        .longitudeDegrees(-117.918669)
                        .altitudeAglMeters(500.0)
                        .build();
                    
                    GeoPolygonPosition geoPos4 = GeoPolygonPosition.builder()
                        .position(pos4)
                        .heightM(1.0f)
                        .build();
                    positions.add(geoPos4);
                    
                    // Create entity objects
                    ControlAreaDetails controlArea = ControlAreaDetails.builder()
                        .type(ControlAreaDetailsType.CONTROL_AREA_TYPE_LOITER_ZONE)
                        .build();
                        
                    GeoDetails geoDetails = GeoDetails.builder()
                        .type(GeoDetailsType.GEO_TYPE_CONTROL_AREA)
                        .controlArea(controlArea)
                        .build();
                        
                    LinearRing ring = LinearRing.builder()
                        .positions(positions)
                        .build();
                        
                    GeoPolygon polygon = GeoPolygon.builder()
                        .rings(Arrays.asList(ring))
                        .build();
                        
                    GeoShape geoShape = GeoShape.builder()
                        .polygon(polygon)
                        .build();
                    
                    // Create the entity
                    Entity entity = Entity.builder()
                        .entityId(entityId)
                        .description("Polygon entity")
                        .aliases(Aliases.builder()
                            .name("Control-Area Loiter Zone")
                            .build())
                        .isLive(true)
                        .createdTime(OffsetDateTime.ofInstant(creationTime, ZoneOffset.UTC))
                        .noExpiry(true)
                        .ontology(Ontology.builder()
                            .template(OntologyTemplate.TEMPLATE_GEO)
                            .build())
                        .geoDetails(geoDetails)
                        .geoShape(geoShape)
                        .provenance(Provenance.builder()
                            .integrationName("your_integration_name")
                            .dataType("test_data")
                            .sourceUpdateTime(OffsetDateTime.ofInstant(latestTimestamp, ZoneOffset.UTC))
                            .build())
                        .build();
                    
                    // Publish the entity
                    client.entities().publishEntity(entity);
                    System.out.println("Published geo entity ID: " + entityId);

                    // Republishing every 10 seconds
                    Thread.sleep(10000);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    Thread.sleep(10000);
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to initialize: " + e.getMessage());
        }
    }
}
```

```py title={"Python (REST)"} startLine={31} maxLines={68}
from anduril import Lattice, Aliases, GeoDetails, GeoShape, GeoPolygon, \
    GeoPolygonPosition, Position, ControlAreaDetails, LinearRing, Ontology, Provenance
from datetime import datetime, timezone
import asyncio
import os
import sys
from uuid import uuid4

lattice_endpoint = os.getenv('LATTICE_ENDPOINT')
environment_token = os.getenv('ENVIRONMENT_TOKEN')
# Remove sandboxes_token from the following statements if you are not developing on Sandboxes.
sandboxes_token = os.getenv('SANDBOXES_TOKEN')
if not environment_token or not lattice_endpoint or not sandboxes_token:
    print("Missing required environment variables.")
    sys.exit(1)
    
client = Lattice(
    base_url=f"https://{lattice_endpoint}",
    token=lambda: str(environment_token),
    # Remove the following header if you are not developing on Sandboxes.
    headers={ "anduril-sandbox-authorization": f"Bearer {sandboxes_token}" }
)
id = str(uuid4())

async def app():
    try:
        creation_time = datetime.now(timezone.utc)
        # Entities must be republished at least every 5 minutes to persist across Lattice service restarts
        while(True):
            latest_timestamp = datetime.now(timezone.utc)
            client.entities.publish_entity(
                entity_id= id,
                description="Control area",
                aliases=Aliases(
                    name="Loiter Zone 1",
                ),
                is_live=True,
                created_time=creation_time,
                no_expiry=True,
                ontology=Ontology(
                    template="TEMPLATE_GEO"
                ),
                geo_details=GeoDetails(
                    type="GEO_TYPE_CONTROL_AREA",
                    control_area=ControlAreaDetails(
                        type="CONTROL_AREA_TYPE_LOITER_ZONE"
                    )
                ),
                geo_shape=GeoShape(
                    polygon=GeoPolygon(
                        rings=[
                            LinearRing(
                                positions=[
                                    GeoPolygonPosition(
                                        position=Position(
                                            latitude_degrees=33.641132,
                                            longitude_degrees=-117.918669,
                                            altitude_agl_meters=500
                                        ),
                                        height_m=1
                                    ),
                                    GeoPolygonPosition(
                                        position=Position(
                                            latitude_degrees=33.646911,
                                            longitude_degrees=-117.929123,
                                            altitude_agl_meters=500
                                        ),
                                        height_m=1
                                    ),
                                    GeoPolygonPosition(
                                        position=Position(
                                            latitude_degrees=33.635059,
                                            longitude_degrees=-117.917482,
                                            altitude_agl_meters=500
                                        ),
                                        height_m=1
                                    ),
                                    GeoPolygonPosition(
                                        position=Position(
                                            latitude_degrees=33.641132,
                                            longitude_degrees=-117.918669,
                                            altitude_agl_meters=500
                                        ),
                                        height_m=1
                                    )
                                ]
                            )
                        ]
                    )
                ),
                provenance=Provenance(
                    integration_name="your_integration_name",
                    data_type="test_data",
                    source_update_time=latest_timestamp
                )
            )
            # Republish every 5 seconds
            await asyncio.sleep(5)
    except asyncio.CancelledError:
        print(">>>Exiting...")
    except Exception as error:
        print(f"Exception: {error}")

if __name__ == "__main__":
    asyncio.run(app())
```

```ts title={"TypeScript (REST)"} startLine={28} maxLines={70}
import { LatticeClient } from "@anduril-industries/lattice-sdk";
import { v4 as uuidv4 } from 'uuid';

const latticeEndpoint = process.env.LATTICE_ENDPOINT;
const environmentToken = process.env.ENVIRONMENT_TOKEN;

// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
const sandboxesToken = process.env.SANDBOXES_TOKEN;
if (!latticeEndpoint || !environmentToken || !sandboxesToken) {
    console.log('Missing required environment variables.');
    process.exit(1);
}

const client = new LatticeClient(
    {
        baseUrl: `https://${latticeEndpoint}`,
        token: environmentToken,
        // Remove the following if you are not developing on Sandboxes.
        headers: {  "Anduril-Sandbox-Authorization": `Bearer ${sandboxesToken}`  }
    }
);

const entityId = uuidv4()

async function App() {
    try {
        const latestTimestamp = new Date();
        await client.entities.publishEntity(
            {
                entityId: entityId,
                description: "Polygon entity",
                aliases: { name: "Control-Area Loiter Zone" },
                isLive: true,
                createdTime: latestTimestamp.toISOString(),
                noExpiry: true, // Entities with noExpiry still need to be republished every 5 minutes to persist across service restarts
                ontology: {
                    template: "TEMPLATE_GEO"
                },
                geoDetails: {
                    type: "GEO_TYPE_CONTROL_AREA",
                    controlArea: {
                        type: "CONTROL_AREA_TYPE_LOITER_ZONE"
                    }
                },
                geoShape: {
                    polygon: {
                        rings: [
                            {
                                positions: [
                                    {
                                        position: {
                                            latitudeDegrees: 33.641132,
                                            longitudeDegrees: -117.918669,
                                            altitudeAglMeters: 500
                                        },
                                        heightM: 1
                                    },
                                    {
                                        position: {
                                            latitudeDegrees: 33.646911,
                                            longitudeDegrees: -117.929123,
                                            altitudeAglMeters: 500
                                        },
                                        heightM: 1 
                                    },
                                    {
                                        position: {
                                            latitudeDegrees: 33.635059,
                                            longitudeDegrees: -117.917482,
                                            altitudeAglMeters: 500
                                        },
                                        heightM: 1
                                    },
                                    {
                                        position: {
                                            latitudeDegrees: 33.641132,
                                            longitudeDegrees: -117.918669,
                                            altitudeAglMeters: 500
                                        },
                                        heightM: 1
                                    }
                                ]
                            }
                        ]
                    }
                },
                provenance: {
                    integrationName: "your_integration_name",
                    dataType: "your_data_type",
                    sourceUpdateTime: latestTimestamp.toISOString()
                }
            }
        );
        console.log(`Publishing geo entity.`);
    } catch (error) {
        console.log(`Encountered the following error while publishing entity: ${error}`);
    }
}
(async function runIndefinitely() {
    while (true) {
        await App();
        // Wait for 10 seconds before the next iteration
        // Republishing entities at least every 5 minutes is required for them to persist across Lattice service restarts
        // This example republishes every 10 seconds, well within the 5-minute requirement
        await new Promise(resolve => setTimeout(resolve, 10000));
    }
})();

```

```rs title={"Rust (REST)"} startLine={58} maxLines={51}
use anduril_lattice_sdk::prelude::*;

use std::env;
use std::time::Duration;
use uuid::Uuid;

/// Build a single polygon vertex at the given position, 1 meter tall.
fn polygon_position(lat: f64, lon: f64) -> GeoPolygonPosition {
    GeoPolygonPosition {
        position: Some(Position {
            latitude_degrees: Some(lat),
            longitude_degrees: Some(lon),
            altitude_agl_meters: Some(500.0),
            ..Default::default()
        }),
        height_m: Some(1.0),
        ..Default::default()
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    // Remove sandboxes_token if you are not developing on Sandboxes.
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    if environment_token.is_empty() || lattice_endpoint.is_empty() || sandboxes_token.is_empty() {
        eprintln!("Missing required environment variables:");
        eprintln!("  LATTICE_ENDPOINT");
        eprintln!("  ENVIRONMENT_TOKEN");
        eprintln!("  SANDBOXES_TOKEN");
        std::process::exit(1);
    }

    let config = ClientConfig {
        base_url: format!("https://{}", lattice_endpoint),
        token: Some(environment_token),
        // Remove custom_headers if you are not developing on Sandboxes.
        custom_headers: HashMap::from([(
            "anduril-sandbox-authorization".to_string(),
            format!("Bearer {}", sandboxes_token),
        )]),
        ..Default::default()
    };
    let client = Lattice::new(config)?;

    let id = Uuid::new_v4().to_string();

    let creation_time = Utc::now().fixed_offset();
    // Entities must be republished at least every 5 minutes to persist across
    // Lattice service restarts.
    loop {
        let latest_timestamp = Utc::now().fixed_offset();
        let entity = Entity {
            entity_id: Some(id.clone()),
            description: Some("Control area".to_string()),
            aliases: Some(Aliases {
                name: Some("Loiter Zone 1".to_string()),
                ..Default::default()
            }),
            is_live: Some(true),
            created_time: Some(creation_time),
            no_expiry: Some(true),
            ontology: Some(Ontology {
                template: Some(OntologyTemplate::TemplateGeo),
                ..Default::default()
            }),
            geo_details: Some(GeoDetails {
                r#type: Some(GeoDetailsType::GeoTypeControlArea),
                control_area: Some(ControlAreaDetails {
                    r#type: Some(ControlAreaDetailsType::ControlAreaTypeLoiterZone),
                }),
                ..Default::default()
            }),
            geo_shape: Some(GeoShape {
                polygon: Some(GeoPolygon {
                    rings: Some(vec![LinearRing {
                        positions: Some(vec![
                            polygon_position(33.641132, -117.918669),
                            polygon_position(33.646911, -117.929123),
                            polygon_position(33.635059, -117.917482),
                            polygon_position(33.641132, -117.918669),
                        ]),
                        ..Default::default()
                    }]),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            provenance: Some(Provenance {
                integration_name: Some("your_integration_name".to_string()),
                data_type: Some("test_data".to_string()),
                source_update_time: Some(latest_timestamp),
                ..Default::default()
            }),
            ..Default::default()
        };

        if let Err(e) = client.entities.publish_entity(&entity, None).await {
            eprintln!("Exception: {}", e);
        }

        // Republish every 5 seconds.
        tokio::time::sleep(Duration::from_secs(5)).await;
    }
}

```

```go title={"Go (gRPC)"} startLine={109} maxLines={55}
// This Go example is compatible with artifacts generated using
// the following grpc/go plugin: https://buf.build/anduril/lattice-sdk/sdks/main:grpc/go
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/grpc/go/anduril/entitymanager/v1/entitymanagerv1grpc"
	entitymanagerv1 "schema-registry.developer.anduril.com/gen/go/anduril/lattice-sdk/protocolbuffers/go/anduril/entitymanager/v1"
	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/protobuf/types/known/timestamppb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

func main() {
	// Get environment variables
	environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
	latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
	sandboxesToken := os.Getenv("SANDBOXES_TOKEN")

	// Check required environment variables
	if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
		fmt.Println("Missing required environment variables")
		os.Exit(1)
	}

	// Setup authentication
	auth := &BearerTokenAuth{
		Token:          environmentToken,
		SandboxesToken: sandboxesToken,
	}

	// Setup gRPC connection options
	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
		grpc.WithPerRPCCredentials(auth),
	}

	// Create gRPC connection
	conn, err := grpc.NewClient(latticeEndpoint, opts...)
	if err != nil {
		log.Fatalf("Did not connect: %v", err)
	}
	defer conn.Close()

	// Create EntityManager client
	client := entitymanagerv1grpc.NewEntityManagerAPIClient(conn)

	// Generate a unique ID for the entity
	entityId := uuid.New().String()

	// Get creation time
	creationTime := time.Now().UTC()
	creationTimestamp := timestamppb.New(creationTime)

	// Create positions for the polygon
	positions := []*entitymanagerv1.GeoPolygonPosition{
		// First point
		{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:   33.641132,
				LongitudeDegrees:  -117.918669,
				AltitudeAglMeters: wrapperspb.Double(500),
			},
			HeightM: wrapperspb.Float(1),
		},
		// Second point
		{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:   33.646911,
				LongitudeDegrees:  -117.929123,
				AltitudeAglMeters: wrapperspb.Double(500),
			},
			HeightM: wrapperspb.Float(1),
		},
		// Third point
		{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:   33.635059,
				LongitudeDegrees:  -117.917482,
				AltitudeAglMeters: wrapperspb.Double(500),
			},
			HeightM: wrapperspb.Float(1),
		},
		// Fourth point (same as first to close the polygon)
		{
			Position: &entitymanagerv1.Position{
				LatitudeDegrees:   33.641132,
				LongitudeDegrees:  -117.918669,
				AltitudeAglMeters: wrapperspb.Double(500),
			},
			HeightM: wrapperspb.Float(1),
		},
	}

	// Continuously publish the entity
	for {
		// Get current timestamp for this update
		latestTimestamp := time.Now().UTC()
		ctx := context.Background()

		// Create entity to publish
		entity := &entitymanagerv1.Entity{
			EntityId:    entityId,
			Description: "Polygon entity",
			Aliases: &entitymanagerv1.Aliases{
				Name: "Control-Area Loiter Zone",
			},
			IsLive:      true,
			CreatedTime: creationTimestamp,
			NoExpiry:    true,
			Ontology: &entitymanagerv1.Ontology{
				Template: entitymanagerv1.Template_TEMPLATE_GEO,
			},
			GeoDetails: &entitymanagerv1.GeoDetails{
				Type: entitymanagerv1.GeoType_GEO_TYPE_CONTROL_AREA,
				TypeDetails: &entitymanagerv1.GeoDetails_ControlArea{
					ControlArea: &entitymanagerv1.ControlAreaDetails{
						Type: entitymanagerv1.ControlAreaType_CONTROL_AREA_TYPE_LOITER_ZONE,
					},
				},
			},
			GeoShape: &entitymanagerv1.GeoShape{
				Shape: &entitymanagerv1.GeoShape_Polygon{
					Polygon: &entitymanagerv1.GeoPolygon{
						Rings: []*entitymanagerv1.LinearRing{
							{
								Positions: positions,
							},
						},
					},
				},
			},
			Provenance: &entitymanagerv1.Provenance{
				IntegrationName:  "your_integration_name",
				DataType:         "test_data",
				SourceUpdateTime: timestamppb.New(latestTimestamp),
			},
		}

		// Create publish request
		request := &entitymanagerv1.PublishEntityRequest{
			Entity: entity,
		}

		// Publish the entity
		_, err := client.PublishEntity(ctx, request)

		// Handle errors
		if err != nil {
			fmt.Printf("Error publishing entity: %v\n", err)
		} else {
			fmt.Println("Publishing geo entity")
		}

		// Republishing every 10 seconds
		time.Sleep(10 * time.Second)
	}
}

```

```py title={"Python (gRPC)"} startLine={93} maxLines={40}
# This Python example is compatible with artifacts generated using the following
# Buf plugins: https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:bufbuild/py
# and https://schema-registry.developer.anduril.com/anduril/lattice-sdk/sdks/main:connectrpc/py

import os
import sys
import time
import uuid
from datetime import datetime, timezone
from bearer_auth import create_client
from protobuf import Oneof
from protobuf.wkt import DoubleValue, FloatValue, Timestamp

from anduril.entitymanager.v1.entity_pub_pb import Aliases, Entity, Provenance
from anduril.entitymanager.v1.entity_manager_api_pub_pb import PublishEntityRequest
from anduril.entitymanager.v1.entity_manager_api_pub_connect import EntityManagerAPIClientSync
from anduril.entitymanager.v1.geoentity_pub_pb import (
    ControlAreaDetails,
    ControlAreaType,
    GeoDetails,
    GeoPolygon,
    GeoPolygonPosition,
    GeoShape,
    GeoType,
    LinearRing,
)
from anduril.entitymanager.v1.location_pub_pb import Position
from anduril.entitymanager.v1.ontology_pub_pb import Ontology
from anduril.entitymanager.v1.types_pub_pb import Template


def to_timestamp(dt: datetime) -> Timestamp:
    return Timestamp.from_datetime(dt)


def main():
    environment_token = os.getenv("ENVIRONMENT_TOKEN")
    lattice_endpoint = os.getenv("LATTICE_ENDPOINT")
    sandboxes_token = os.getenv("SANDBOXES_TOKEN")

    if not environment_token or not lattice_endpoint or not sandboxes_token:
        print("Missing required environment variables", file=sys.stderr)
        sys.exit(1)

    # Create the API client over Connect gRPC with authentication
    client = create_client(EntityManagerAPIClientSync, lattice_endpoint, environment_token, sandboxes_token)

    entity_id = str(uuid.uuid4())
    creation_timestamp = to_timestamp(datetime.now(timezone.utc))

    positions = [
        # First point
        GeoPolygonPosition(
            position=Position(
                latitude_degrees=33.641132,
                longitude_degrees=-117.918669,
                altitude_agl_meters=DoubleValue(value=500.0),
            ),
            height_m=FloatValue(value=1.0),
        ),
        # Second point
        GeoPolygonPosition(
            position=Position(
                latitude_degrees=33.646911,
                longitude_degrees=-117.929123,
                altitude_agl_meters=DoubleValue(value=500.0),
            ),
            height_m=FloatValue(value=1.0),
        ),
        # Third point
        GeoPolygonPosition(
            position=Position(
                latitude_degrees=33.635059,
                longitude_degrees=-117.917482,
                altitude_agl_meters=DoubleValue(value=500.0),
            ),
            height_m=FloatValue(value=1.0),
        ),
        # Fourth point (same as first to close the polygon)
        GeoPolygonPosition(
            position=Position(
                latitude_degrees=33.641132,
                longitude_degrees=-117.918669,
                altitude_agl_meters=DoubleValue(value=500.0),
            ),
            height_m=FloatValue(value=1.0),
        ),
    ]

    while True:
        latest_ts = to_timestamp(datetime.now(timezone.utc))

        entity = Entity(
            entity_id=entity_id,
            description="Polygon entity",
            aliases=Aliases(name="Control-Area Loiter Zone"),
            is_live=True,
            created_time=creation_timestamp,
            no_expiry=True,
            ontology=Ontology(template=Template.GEO),
            geo_details=GeoDetails(
                type=GeoType.CONTROL_AREA,
                type_details=Oneof(
                    "control_area",
                    ControlAreaDetails(
                        type=ControlAreaType.LOITER_ZONE,
                    ),
                ),
            ),
            geo_shape=GeoShape(
                shape=Oneof(
                    "polygon",
                    GeoPolygon(
                        rings=[LinearRing(positions=positions)],
                    ),
                ),
            ),
            provenance=Provenance(
                integration_name="your_integration_name",
                data_type="test_data",
                source_update_time=latest_ts,
            ),
        )

        try:
            client.publish_entity(PublishEntityRequest(entity=entity))
            print("Publishing geo entity")
        except Exception as error:
            print(f"Error publishing entity: {error}", file=sys.stderr)

        # Republishing every 10 seconds
        time.sleep(10)


if __name__ == "__main__":
    main()

```

```rs title={"Rust (gRPC)"} startLine={116} maxLines={48}
// This Rust example is compatible with artifacts generated using
// the following grpc/rust plugin: https://buf.build/anduril/lattice-sdk/sdks/main:community/neoeinstein-tonic
mod bearer_auth;

use anduril_lattice_sdk_community_neoeinstein_prost::anduril::entitymanager::v1::{
    geo_details, geo_shape, Aliases, ControlAreaDetails, ControlAreaType, Entity, GeoDetails,
    GeoPolygon, GeoPolygonPosition, GeoShape, GeoType, LinearRing, Ontology, Position, Provenance,
    PublishEntityRequest, Template,
};
use anduril_lattice_sdk_community_neoeinstein_tonic::anduril::entitymanager::v1::tonic::entity_manager_api_client::EntityManagerApiClient;
use bearer_auth::EnvironmentTokenAuth;
use prost_types::Timestamp;
use tonic::metadata::MetadataValue;
use tonic::transport::{Channel, ClientTlsConfig};
use tonic::Request;
use uuid::Uuid;

use std::env;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

fn now_timestamp() -> Timestamp {
    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    Timestamp {
        seconds: d.as_secs() as i64,
        nanos: d.subsec_nanos() as i32,
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let environment_token = env::var("ENVIRONMENT_TOKEN")
        .expect("ENVIRONMENT_TOKEN environment variable not set");
    let lattice_endpoint = env::var("LATTICE_ENDPOINT")
        .expect("LATTICE_ENDPOINT environment variable not set");
    let sandboxes_token = env::var("SANDBOXES_TOKEN")
        .expect("SANDBOXES_TOKEN environment variable not set");

    let auth = EnvironmentTokenAuth::new(
        environment_token,
        sandboxes_token,
    );

    let tls_config = ClientTlsConfig::new().with_native_roots();
    let channel = Channel::from_shared(format!("https://{}", lattice_endpoint))?
        .tls_config(tls_config)?
        .connect()
        .await?;

    let access_token = auth.get_token().await?;
    let sandboxes_token = auth.sandboxes_token();
    let auth_header: MetadataValue<_> = format!("Bearer {}", access_token).parse()?;
    let sandbox_header: MetadataValue<_> = format!("Bearer {}", sandboxes_token).parse()?;

    let mut client = EntityManagerApiClient::with_interceptor(
        channel,
        move |mut req: Request<()>| {
            req.metadata_mut()
                .insert("authorization", auth_header.clone());
            req.metadata_mut()
                .insert("anduril-sandbox-authorization", sandbox_header.clone());
            Ok(req)
        },
    );

    let entity_id = Uuid::new_v4().to_string();
    let creation_timestamp = now_timestamp();

    // Create positions for the polygon
    let positions = vec![
        // First point
        GeoPolygonPosition {
            position: Some(Position {
                latitude_degrees: 33.641132,
                longitude_degrees: -117.918669,
                altitude_agl_meters: Some(500.0),
                ..Default::default()
            }),
            height_m: Some(1.0),
        },
        // Second point
        GeoPolygonPosition {
            position: Some(Position {
                latitude_degrees: 33.646911,
                longitude_degrees: -117.929123,
                altitude_agl_meters: Some(500.0),
                ..Default::default()
            }),
            height_m: Some(1.0),
        },
        // Third point
        GeoPolygonPosition {
            position: Some(Position {
                latitude_degrees: 33.635059,
                longitude_degrees: -117.917482,
                altitude_agl_meters: Some(500.0),
                ..Default::default()
            }),
            height_m: Some(1.0),
        },
        // Fourth point (same as first to close the polygon)
        GeoPolygonPosition {
            position: Some(Position {
                latitude_degrees: 33.641132,
                longitude_degrees: -117.918669,
                altitude_agl_meters: Some(500.0),
                ..Default::default()
            }),
            height_m: Some(1.0),
        },
    ];

    // Continuously publish the entity
    loop {
        let latest_timestamp = now_timestamp();

        let entity = Entity {
            entity_id: entity_id.clone(),
            description: "Polygon entity".to_string(),
            aliases: Some(Aliases {
                name: "Control-Area Loiter Zone".to_string(),
                ..Default::default()
            }),
            is_live: true,
            created_time: Some(creation_timestamp.clone()),
            no_expiry: true,
            ontology: Some(Ontology {
                template: Template::Geo as i32,
                ..Default::default()
            }),
            geo_details: Some(GeoDetails {
                r#type: GeoType::ControlArea as i32,
                type_details: Some(geo_details::TypeDetails::ControlArea(ControlAreaDetails {
                    r#type: ControlAreaType::LoiterZone as i32,
                })),
                visual_details: None,
            }),
            geo_shape: Some(GeoShape {
                shape: Some(geo_shape::Shape::Polygon(GeoPolygon {
                    rings: vec![LinearRing {
                        positions: positions.clone(),
                    }],
                    is_rectangle: false,
                })),
            }),
            provenance: Some(Provenance {
                integration_name: "your_integration_name".to_string(),
                data_type: "test_data".to_string(),
                source_update_time: Some(latest_timestamp.clone()),
                ..Default::default()
            }),
            ..Default::default()
        };

        let request = Request::new(PublishEntityRequest {
            entity: Some(entity),
        });
        match client.publish_entity(request).await {
            Ok(_) => println!("Publishing geo entity"),
            Err(e) => eprintln!("Error publishing entity: {}", e),
        }

        // Republish every 10 seconds
        tokio::time::sleep(Duration::from_secs(10)).await;
    }
}

```

The example sets [`noExpiry`](/reference/rest/entities/publish-entity#request.body.noExpiry) instead
of `expiryTime`, so the polygon persists until you delete it. For more information, see
[Keep shapes on the map](#keep-shapes-on-the-map).

## Model other shapes

The other shapes use the same components as a polygon, with a different `geo_shape`:

#### Point

A `point` marks a single position, such as a rally point or a landing site. Set its position
in `geoShape.point.position`:

**`point.json`**

```json title="point.json" maxLines=25
{
    "entityId": "UNIQUE_ENTITY_ID",
    "description": "Geo point",
    "isLive": true,
    "createdTime": "2024-12-07T00:45:15.581592Z",
    "noExpiry": true,
    "provenance": {
        "integrationName": "your_integration_name",
        "dataType": "your_data_type",
        "sourceUpdateTime": "2025-04-07T00:19:47.706196Z"
    },
    "geoShape": {
    "point": {
        "position": {
            "latitudeDegrees": 50.91402185768586,
            "longitudeDegrees": 0.79203612077257,
            "altitudeHaeMeters": 46.214997987295234,
            "altitudeAglMeters": 0.5000067609670396
        }
    }
    },
    "geoDetails": {
        "type": "GEO_TYPE_GENERAL"
    },
    "aliases": {
        "name": "Point"
    },
    "ontology": {
        "template": "TEMPLATE_GEO"
    }
}
```

#### Line

A `line` connects two or more positions, such as a route or a boundary. List the positions in
order in `geoShape.line.positions`:

**`line.json`**

```json title="line.json" maxLines=25
{
    "entityId": "UNIQUE_ENTITY_ID",
    "description": "Geo line",
    "isLive": true,
    "createdTime": "2024-12-07T01:08:39.079826Z",
    "expiryTime": "2024-12-07T01:13:39.079828Z",
    "provenance": {
        "integrationName": "your_integration_name",
        "dataType": "your_data_type",
        "sourceUpdateTime": "2025-04-07T00:19:47.706196Z"
    },
    "geoShape": {
        "line": {
            "positions": [
            {
                "latitudeDegrees": 47.605,
                "longitudeDegrees": -122.329
            },
            {
                "latitudeDegrees": 47.61,
                "longitudeDegrees": -122.33
            }
            ]
        }
    },
    "geoDetails": {
        "type": "GEO_TYPE_GENERAL"
    },
    "aliases": {
        "name": "Line"
    },
    "ontology": {
        "template": "TEMPLATE_GEO"
    }
}
```

#### Ellipse

An `ellipse` describes a circular or oval area around a center point, such as a keep-out
radius. Set the center in `location`, and set the axes in meters and the orientation in degrees
in `geoShape.ellipse`. Equal axes produce a circle:

**`ellipse.json`**

```json title="ellipse.json" maxLines=25
{
    "entityId": "UNIQUE_ENTITY_ID",
    "description": "Geo ellipse",
    "isLive": true,
    "createdTime": "2024-12-07T01:06:32.834952Z",
    "expiryTime": "2024-12-07T01:11:32.834954Z",
    "aliases": {
        "name": "Ellipse"
    },
    "ontology": {
        "template": "TEMPLATE_GEO"
    },
    "provenance": {
        "integrationName": "your_integration_name",
        "dataType": "your_data_type",
        "sourceUpdateTime": "2025-04-07T00:19:47.706196Z"
    },
    "geoDetails": {
        "type": "GEO_TYPE_CONTROL_AREA"
    },
    "geoShape": {
        "ellipse": {
            "semiMajorAxisM": 20,
            "semiMinorAxisM": 20,
            "orientationD": 40
        }
    },
    "location": {
        "position": {
            "latitudeDegrees": 51.46,
            "longitudeDegrees": -0.16
        }
    }
}
```

## Keep shapes on the map

Most geo-entities describe areas that stay relevant across many operations, such as airfields and
control areas. For these shapes, set `noExpiry` to `true` instead of setting an `expiryTime`. Use
`noExpiry` *only* when the entity contains information that other tasks or integrations need beyond
its immediate operational context. Don't set both `noExpiry` and `expiryTime`. Lattice rejects an
entity that sets both.

> **Warning**
>
> Even with `noExpiry` set to `true`, republish the entity at least every 5 minutes. If Lattice
> restarts and an entity hasn't been republished within the previous 5 minutes, Lattice doesn't
> restore it. The example code republishes the polygon in an indefinite loop.

To remove a shape, publish it again with `isLive` set to `false`.

## What's next?

* Use geo-entities as control areas when you [task an asset](/guides/tasks/overview).
* Follow shapes and tracks as they change with [Cue and monitor](/guides/entities/cue-and-monitor).
* Explore every geo-entity field in the [`PublishEntity` API reference](/reference/rest/entities/publish-entity).