# Create Geofence

Last updated:

<!-- -->

October 18, 2026

<!-- -->

\| 6 minutes read

<br />

<br />

Learn how to create different types of geofences (circular, rectangular, and polygon) for monitoring asset movements.

## Overview[​](#overview "Direct link to Overview")

Geofences are virtual boundaries that trigger events when assets enter or exit them. This example demonstrates creating three common geofence types.

## Use Case[​](#use-case "Direct link to Use Case")

A logistics company needs to monitor:

* A **circular zone** around a warehouse (200m radius)
* A **rectangular parking area** for fleet vehicles
* A **polygon delivery zone** covering downtown streets

## Example Request[​](#example-request "Direct link to Example Request")

### Create Multiple Geofences[​](#create-multiple-geofences "Direct link to Create Multiple Geofences")

* cURL
* JavaScript

```bash
curl -X POST https://api.magiclane.net/api/v1/add_geofence_area \
  -H "Authorization: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "geofences": [
      {
        "p_id": "warehouse_zone",
        "p_type": "circle",
        "p_name": "Main Warehouse Safety Zone",
        "p_keywords": ["warehouse", "safety", "restricted"],
        "p_properties": {
          "facility_name": "Main Distribution Center",
          "alert_on_exit": true
        },
        "p_geojson": {
          "type": "Circle",
          "coordinates": [[[25.611922, 45.646986], [200, 200]]]
        }
      },
      {
        "p_id": "parking_area",
        "p_type": "rectangle",
        "p_name": "Fleet Parking Lot",
        "p_keywords": ["parking", "fleet"],
        "p_properties": {
          "capacity": 50,
          "access": "authorized_only"
        },
        "p_geojson": {
          "type": "Rectangle",
          "coordinates": [[[25.609518, 45.641346], [25.615669, 45.644040]]]
        }
      },
      {
        "p_id": "delivery_zone",
        "p_type": "polygon",
        "p_name": "Downtown Delivery Zone",
        "p_keywords": ["delivery", "downtown"],
        "p_properties": {
          "zone_type": "commercial",
          "priority": "high"
        },
        "p_geojson": {
          "type": "Polygon",
          "coordinates": [[
            [25.612887, 45.647265],
            [25.620123, 45.645678],
            [25.618456, 45.642123],
            [25.610234, 45.643890],
            [25.612887, 45.647265]
          ]]
        }
      }
    ]
  }'

```

```javascript
const createMultipleGeofences = async () => {
  const response = await fetch(
    'https://api.magiclane.net/api/v1/add_geofence_area',
    {
      method: 'POST',
      headers: {
        'Authorization': 'YOUR_API_KEY',
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        geofences: [
          {
            p_id: "warehouse_zone",
            p_type: "circle",
            p_name: "Main Warehouse Safety Zone",
            p_keywords: ["warehouse", "safety", "restricted"],
            p_properties: {
              facility_name: "Main Distribution Center",
              alert_on_exit: true
            },
            p_geojson: {
              type: "Circle",
              coordinates: [[[25.611922, 45.646986], [200, 200]]]
            }
          },
          {
            p_id: "parking_area",
            p_type: "rectangle",
            p_name: "Fleet Parking Lot",
            p_keywords: ["parking", "fleet"],
            p_properties: {
              capacity: 50,
              access: "authorized_only"
            },
            p_geojson: {
              type: "Rectangle",
              coordinates: [[[25.609518, 45.641346], [25.615669, 45.644040]]]
            }
          },
          {
            p_id: "delivery_zone",
            p_type: "polygon",
            p_name: "Downtown Delivery Zone",
            p_keywords: ["delivery", "downtown"],
            p_properties: {
              zone_type: "commercial",
              priority: "high"
            },
            p_geojson: {
              type: "Polygon",
              coordinates: [[
                [25.612887, 45.647265],
                [25.620123, 45.645678],
                [25.618456, 45.642123],
                [25.610234, 45.643890],
                [25.612887, 45.647265]
              ]]
            }
          }
        ]
      })
    }
  );

  const result = await response.json();
  
  // Check results
  result.geofence_ids.forEach(geo => {
    if (geo.error) {
      console.error(`❌ Failed to create ${geo.id}: ${geo.error}`);
    } else {
      console.log(`✅ Created: ${geo.id}`);
    }
  });
  
  return result;
};

await createMultipleGeofences();

```

**Response** (code `200 OK`)

```json
{
  "geofence_ids": [
    {
      "id": "warehouse_zone",
      "error": ""
    },
    {
      "id": "parking_area",
      "error": ""
    },
    {
      "id": "delivery_zone",
      "error": ""
    }
  ]
}

```

## Key Concepts[​](#key-concepts "Direct link to Key Concepts")

### Geofence Types[​](#geofence-types "Direct link to Geofence Types")

1. **Circle**

   * Defined by center point and radius
   * Format: `[[[longitude, latitude], [radius_m, radius_m]]]`
   * Best for: Point-based areas (warehouses, stores)

2. **Rectangle**

   * Defined by min/max coordinates
   * Format: `[[[min_lon, min_lat], [max_lon, max_lat]]]`
   * Best for: Buildings, parking lots

3. **Polygon**

   * Defined by coordinate array
   * First and last points must match (closed polygon)
   * Best for: Irregular shapes, delivery zones

### Keywords for Monitoring[​](#keywords-for-monitoring "Direct link to Keywords for Monitoring")

Use `p_keywords` to:

* Group related geofences for monitoring rules
* Enable filtered searches

## Understanding Coordinate Formats[​](#understanding-coordinate-formats "Direct link to Understanding Coordinate Formats")

### Circle Geofence[​](#circle-geofence "Direct link to Circle Geofence")

```javascript
// Format: [[[longitude, latitude], [radius_meters, radius_meters]]]
p_geojson: {
  type: "Circle",
  coordinates: [
    [
      [25.611922, 45.646986],  // Center point [lon, lat]
      [200, 200]                // Radius [meters, meters]
    ]
  ]
}

```

### Rectangle Geofence[​](#rectangle-geofence "Direct link to Rectangle Geofence")

```javascript
// Format: [[[min_lon, min_lat], [max_lon, max_lat]]]
p_geojson: {
  type: "Rectangle",
  coordinates: [
    [
      [25.609518, 45.641346],  // Southwest corner [lon, lat]
      [25.615669, 45.644040]   // Northeast corner [lon, lat]
    ]
  ]
}

```

### Polygon Geofence[​](#polygon-geofence "Direct link to Polygon Geofence")

```javascript
// Format: [[lon, lat], [lon, lat], ..., [lon, lat]]
// ⚠️ First and last coordinates must be identical (closed polygon)
p_geojson: {
  type: "Polygon",
  coordinates: [
    [25.612887, 45.647265],  // Point 1
    [25.620123, 45.645678],  // Point 2
    [25.618456, 45.642123],  // Point 3
    [25.610234, 45.643890],  // Point 4
    [25.612887, 45.647265]   // Point 5 (same as Point 1 - closes polygon)
  ]
}

```

## Properties & Keywords Strategy[​](#properties--keywords-strategy "Direct link to Properties & Keywords Strategy")

### Properties for Metadata[​](#properties-for-metadata "Direct link to Properties for Metadata")

Use properties to store additional information about geofences:

```javascript
// Metadata for display and reporting
p_properties: {
  facility_name: "Main Distribution Center",
  zone_type: "commercial",
  priority: "high",
  operating_hours: "24/7",
  capacity: 50,
  alert_on_exit: true
}

```

:::info Properties vs Keywords

* **Properties** store metadata (displayed in UI)
* **Keywords** enable searching and monitor grouping :::

### Keywords for Searching and Monitor Assignment[​](#keywords-for-searching-and-monitor-assignment "Direct link to Keywords for Searching and Monitor Assignment")

Keywords serve two critical purposes: **searching** and **areas monitor grouping**.

#### 1. Searching Geofences[​](#1-searching-geofences "Direct link to 1. Searching Geofences")

Use keywords to find geofences quickly:

```javascript
// Multiple related keywords for flexible searching
p_keywords: [
  "warehouse",      // Type
  "distribution",   // Function
  "restricted",     // Access level
  "24/7"           // Operating hours
]

// Later, search by any keyword
await getGeofencesByKeywords(["warehouse"]);
await getGeofencesByKeywords(["restricted"]);
await getGeofencesByKeywords(["24/7"]);

```

#### 2. Monitor Grouping[​](#2-monitor-grouping "Direct link to 2. Monitor Grouping")

Keywords enable monitors to watch **groups of geofences** without specifying individual IDs:

```javascript
// Step 1: Create geofences with shared keywords
const warehouseGeofences = [
  {
    p_id: "warehouse_north",
    p_keywords: ["warehouse", "loading_dock"],
    // ... other params
  },
  {
    p_id: "warehouse_south",
    p_keywords: ["warehouse", "loading_dock"],
    // ... other params
  },
  {
    p_id: "warehouse_east",
    p_keywords: ["warehouse", "storage"],
    // ... other params
  }
];

// Step 2: Create monitor using keywords (watches ALL matching geofences)
const monitor = {
  p_type: "enter_and_exit_area",
  p_geofence_config: {
    geofence_keywords: ["warehouse"]  // Monitors ALL warehouse zones
  }
};

// This single monitor now tracks entry/exit for:
// - warehouse_north
// - warehouse_south  
// - warehouse_east

```

**Benefits of Keyword-Based Monitoring:**

* ✅ Monitor entire categories without listing individual IDs
* ✅ Simplify configuration for large geofence sets

## Testing Your Geofences[​](#testing-your-geofences "Direct link to Testing Your Geofences")

### Verify Creation[​](#verify-creation "Direct link to Verify Creation")

```javascript
// After creating, verify the geofence exists
const verify = await fetch(
  'https://api.magiclane.net/api/v1/get_geofence_areas',
  {
    method: 'GET',
    headers: {
      'Authorization': 'YOUR_API_KEY',
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      p_ids: ["warehouse_zone"]
    })
  }
);

const geofence = await verify.json();
console.log('Created geofence:', geofence);

```

### Test Point Containment[​](#test-point-containment "Direct link to Test Point Containment")

```javascript
// Check if a test location is inside your geofence
const testLocation = [25.612, 45.647];  // Should be inside warehouse_zone

const containsCheck = await fetch(
  'https://api.magiclane.net/api/v1/geofences_contain_locations',
  {
    method: 'GET',
    headers: {
      'Authorization': 'YOUR_API_KEY',
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify({
      p_geofence_ids: ["warehouse_zone"],
      p_locations: [testLocation]
    })
  }
);

const result = await containsCheck.json();
console.log('Point inside geofence?', result.checked_geofences[0].locations[0].inside);

```

## Notes[​](#notes "Direct link to Notes")

* Use descriptive `p_id` values for easier management
* Add relevant keywords for searching
* Keep polygon areas under 1000 km²
* Close polygon coordinates (first = last point)
* Assign keywords for filtering
* You can create/update a maximum of 1000 geofences per batch request
