ソースを参照

Closes #22620: Add Web Mercator (EPSG:3857) coordinates to sites and devices (#23671)

Arthur Hanson 2 日 前
親
コミット
1505ff583d

+ 7 - 1
docs/models/dcim/device.md

@@ -71,7 +71,13 @@ If installed in a rack, this field indicates the base rack unit in which the dev
 
 
 ### Latitude & Longitude
 ### Latitude & Longitude
 
 
-GPS coordinates of the device for geolocation.
+GPS coordinates of the device for geolocation. These are assumed to use the WGS84 datum (as reported by GPS).
+
+### Web Mercator X & Y
+
+!!! info "This field was introduced in NetBox v4.8."
+
+The device's coordinates in the [Web Mercator](https://epsg.io/3857) (EPSG:3857) projection, in meters. These read-only values are calculated from the latitude and longitude. See the [site](./site.md#web-mercator-x-y) documentation for details.
 
 
 ### Status
 ### Status
 
 

+ 17 - 1
docs/models/dcim/site.md

@@ -48,4 +48,20 @@ The address to use for deliveries destined for the site.
 
 
 ### Latitude & Longitude
 ### Latitude & Longitude
 
 
-GPS coordinates of the site for geolocation.
+GPS coordinates of the site for geolocation. These are assumed to use the WGS84 datum (as reported by GPS).
+
+### Web Mercator X & Y
+
+!!! info "This field was introduced in NetBox v4.8."
+
+The site's [Web Mercator](https://epsg.io/3857) (EPSG:3857) coordinates, in meters. These read-only values are calculated from its latitude and longitude for use with mapping tools:
+
+```
+X = longitude × (π / 180) × 6378137
+Y = ln(tan(π / 4 + latitude × π / 360)) × 6378137
+```
+
+where `ln` is the natural logarithm. Because Web Mercator is undefined at the poles, latitudes beyond ±85.05113° are clamped to that bound.
+
+!!! note
+    Web Mercator (EPSG:3857) differs from the ellipsoidal World Mercator projection (EPSG:3395). Ensure the target system expects EPSG:3857 coordinates.

+ 16 - 5
netbox/dcim/api/serializers_/devices.py

@@ -2,7 +2,7 @@ import decimal
 from functools import cached_property
 from functools import cached_property
 
 
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes.models import ContentType
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 from drf_spectacular.utils import extend_schema_field
 from drf_spectacular.utils import extend_schema_field
 from rest_framework import serializers
 from rest_framework import serializers
 
 
@@ -58,6 +58,16 @@ class DeviceSerializer(PrimaryModelSerializer):
         min_value=decimal.Decimal(0.5),
         min_value=decimal.Decimal(0.5),
         default=None
         default=None
     )
     )
+    mercator_x = serializers.FloatField(
+        read_only=True,
+        allow_null=True,
+        help_text=_('Web Mercator (EPSG:3857) X coordinate, in meters')
+    )
+    mercator_y = serializers.FloatField(
+        read_only=True,
+        allow_null=True,
+        help_text=_('Web Mercator (EPSG:3857) Y coordinate, in meters')
+    )
     status = ChoiceField(choices=DeviceStatusChoices, required=False)
     status = ChoiceField(choices=DeviceStatusChoices, required=False)
     airflow = ChoiceField(choices=DeviceAirflowChoices, allow_blank=True, required=False)
     airflow = ChoiceField(choices=DeviceAirflowChoices, allow_blank=True, required=False)
     cooling_method = ChoiceField(choices=CoolingMethodChoices, allow_blank=True, required=False, allow_null=True)
     cooling_method = ChoiceField(choices=CoolingMethodChoices, allow_blank=True, required=False, allow_null=True)
@@ -115,10 +125,11 @@ class DeviceSerializer(PrimaryModelSerializer):
         model = Device
         model = Device
         fields = [
         fields = [
             'id', 'url', 'display_url', 'display', 'name', 'device_type', 'role', 'tenant', 'platform', 'serial',
             'id', 'url', 'display_url', 'display', 'name', 'device_type', 'role', 'tenant', 'platform', 'serial',
-            'asset_tag', 'site', 'location', 'rack', 'position', 'face', 'latitude', 'longitude', 'parent_device',
-            'status', 'airflow', 'cooling_method', 'primary_ip', 'primary_ip4', 'primary_ip6', 'oob_ip', 'cluster',
-            'virtual_chassis', 'vc_position', 'vc_priority', 'description', 'owner', 'comments', 'config_template',
-            'config_context', 'local_context_data', 'tags', 'custom_fields', 'created', 'last_updated',
+            'asset_tag', 'site', 'location', 'rack', 'position', 'face', 'latitude', 'longitude', 'mercator_x',
+            'mercator_y', 'parent_device', 'status', 'airflow', 'cooling_method', 'primary_ip', 'primary_ip4',
+            'primary_ip6', 'oob_ip', 'cluster', 'virtual_chassis', 'vc_position', 'vc_priority', 'description', 'owner',
+            'comments', 'config_template', 'config_context', 'local_context_data', 'tags', 'custom_fields', 'created',
+            'last_updated',
             'console_port_count', 'console_server_port_count', 'power_port_count', 'power_outlet_count',
             'console_port_count', 'console_server_port_count', 'power_port_count', 'power_outlet_count',
             'cooling_intake_count', 'cooling_outflow_count', 'interface_count', 'front_port_count', 'rear_port_count',
             'cooling_intake_count', 'cooling_outflow_count', 'interface_count', 'front_port_count', 'rear_port_count',
             'device_bay_count', 'module_bay_count', 'inventory_item_count', 'replicate_components',
             'device_bay_count', 'module_bay_count', 'inventory_item_count', 'replicate_components',

+ 14 - 3
netbox/dcim/api/serializers_/sites.py

@@ -1,3 +1,4 @@
+from django.utils.translation import gettext_lazy as _
 from rest_framework import serializers
 from rest_framework import serializers
 from timezone_field.rest_framework import TimeZoneSerializerField
 from timezone_field.rest_framework import TimeZoneSerializerField
 
 
@@ -53,6 +54,16 @@ class SiteSerializer(PrimaryModelSerializer):
     group = SiteGroupSerializer(nested=True, required=False, allow_null=True)
     group = SiteGroupSerializer(nested=True, required=False, allow_null=True)
     tenant = TenantSerializer(nested=True, required=False, allow_null=True)
     tenant = TenantSerializer(nested=True, required=False, allow_null=True)
     time_zone = TimeZoneSerializerField(required=False, allow_null=True)
     time_zone = TimeZoneSerializerField(required=False, allow_null=True)
+    mercator_x = serializers.FloatField(
+        read_only=True,
+        allow_null=True,
+        help_text=_('Web Mercator (EPSG:3857) X coordinate, in meters')
+    )
+    mercator_y = serializers.FloatField(
+        read_only=True,
+        allow_null=True,
+        help_text=_('Web Mercator (EPSG:3857) Y coordinate, in meters')
+    )
     asns = SerializedPKRelatedField(
     asns = SerializedPKRelatedField(
         queryset=ASN.objects.all(),
         queryset=ASN.objects.all(),
         serializer=ASNSerializer,
         serializer=ASNSerializer,
@@ -73,9 +84,9 @@ class SiteSerializer(PrimaryModelSerializer):
         model = Site
         model = Site
         fields = [
         fields = [
             'id', 'url', 'display_url', 'display', 'name', 'slug', 'status', 'region', 'group', 'tenant', 'facility',
             'id', 'url', 'display_url', 'display', 'name', 'slug', 'status', 'region', 'group', 'tenant', 'facility',
-            'time_zone', 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'owner',
-            'comments', 'asns', 'tags', 'custom_fields', 'created', 'last_updated', 'circuit_count', 'device_count',
-            'prefix_count', 'rack_count', 'virtualmachine_count', 'vlan_count',
+            'time_zone', 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'mercator_x',
+            'mercator_y', 'owner', 'comments', 'asns', 'tags', 'custom_fields', 'created', 'last_updated',
+            'circuit_count', 'device_count', 'prefix_count', 'rack_count', 'virtualmachine_count', 'vlan_count',
         ]
         ]
         brief_fields = ('id', 'url', 'display', 'name', 'description', 'slug')
         brief_fields = ('id', 'url', 'display', 'name', 'description', 'slug')
 
 

+ 10 - 0
netbox/dcim/constants.py

@@ -8,6 +8,16 @@ from .choices import InterfaceTypeChoices
 DEVICETYPE_IMAGE_FORMATS = 'image/bmp,image/gif,image/jpeg,image/png,image/tiff,image/webp'
 DEVICETYPE_IMAGE_FORMATS = 'image/bmp,image/gif,image/jpeg,image/png,image/tiff,image/webp'
 
 
 
 
+#
+# Sites
+#
+
+# WGS84 semi-major axis (meters), used as the sphere radius for Web Mercator (EPSG:3857)
+WEB_MERCATOR_EARTH_RADIUS = 6378137
+# Latitude bounds of Web Mercator, at which the projection is square
+WEB_MERCATOR_MAX_LATITUDE = 85.05112877980659
+
+
 #
 #
 # Racks
 # Racks
 #
 #

+ 14 - 0
netbox/dcim/graphql/mixins.py

@@ -1,6 +1,7 @@
 from typing import TYPE_CHECKING, Annotated
 from typing import TYPE_CHECKING, Annotated
 
 
 import strawberry
 import strawberry
+import strawberry_django
 
 
 if TYPE_CHECKING:
 if TYPE_CHECKING:
     from circuits.graphql.types import CircuitTerminationType, ProviderNetworkType, VirtualCircuitTerminationType
     from circuits.graphql.types import CircuitTerminationType, ProviderNetworkType, VirtualCircuitTerminationType
@@ -19,6 +20,7 @@ if TYPE_CHECKING:
 __all__ = (
 __all__ = (
     'CabledObjectMixin',
     'CabledObjectMixin',
     'PathEndpointMixin',
     'PathEndpointMixin',
+    'WebMercatorMixin',
 )
 )
 
 
 
 
@@ -61,3 +63,15 @@ class PathEndpointMixin:
             strawberry.union("ConnectedEndpointType"),
             strawberry.union("ConnectedEndpointType"),
         ]
         ]
     ]
     ]
+
+
+@strawberry.type
+class WebMercatorMixin:
+
+    @strawberry_django.field(only=['latitude', 'longitude'])
+    def mercator_x(self) -> float | None:
+        return self.mercator_x
+
+    @strawberry_django.field(only=['latitude', 'longitude'])
+    def mercator_y(self) -> float | None:
+        return self.mercator_y

+ 3 - 3
netbox/dcim/graphql/types.py

@@ -26,7 +26,7 @@ from utilities.querysets import RestrictedPrefetch
 from virtualization.models import Cluster, VMInterface
 from virtualization.models import Cluster, VMInterface
 
 
 from .filters import *
 from .filters import *
-from .mixins import CabledObjectMixin, PathEndpointMixin
+from .mixins import CabledObjectMixin, PathEndpointMixin, WebMercatorMixin
 
 
 if TYPE_CHECKING:
 if TYPE_CHECKING:
     from circuits.graphql.types import CircuitTerminationType
     from circuits.graphql.types import CircuitTerminationType
@@ -327,7 +327,7 @@ class ConsoleServerPortTemplateType(ModularComponentTemplateType):
     filters=DeviceFilter,
     filters=DeviceFilter,
     pagination=True
     pagination=True
 )
 )
-class DeviceType(ConfigContextMixin, ImageAttachmentsMixin, ContactsMixin, PrimaryObjectType):
+class DeviceType(ConfigContextMixin, ImageAttachmentsMixin, ContactsMixin, WebMercatorMixin, PrimaryObjectType):
     console_port_count: BigInt
     console_port_count: BigInt
     console_server_port_count: BigInt
     console_server_port_count: BigInt
     power_port_count: BigInt
     power_port_count: BigInt
@@ -1145,7 +1145,7 @@ class RegionType(VLANGroupsMixin, ContactsMixin, NestedLtreeGroupObjectType):
     filters=SiteFilter,
     filters=SiteFilter,
     pagination=True
     pagination=True
 )
 )
-class SiteType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, PrimaryObjectType):
+class SiteType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, WebMercatorMixin, PrimaryObjectType):
     time_zone: str | None
     time_zone: str | None
     region: Annotated["RegionType", strawberry.lazy('dcim.graphql.types')] | None
     region: Annotated["RegionType", strawberry.lazy('dcim.graphql.types')] | None
     group: Annotated["SiteGroupType", strawberry.lazy('dcim.graphql.types')] | None
     group: Annotated["SiteGroupType", strawberry.lazy('dcim.graphql.types')] | None

+ 2 - 1
netbox/dcim/models/devices.py

@@ -36,7 +36,7 @@ from utilities.prefetch import get_prefetchable_fields
 from utilities.tracking import TrackingModelMixin
 from utilities.tracking import TrackingModelMixin
 
 
 from .device_components import *
 from .device_components import *
-from .mixins import RenderConfigMixin
+from .mixins import RenderConfigMixin, WebMercatorMixin
 from .modules import Module
 from .modules import Module
 
 
 __all__ = (
 __all__ = (
@@ -553,6 +553,7 @@ class Device(
     ContactsMixin,
     ContactsMixin,
     ImageAttachmentsMixin,
     ImageAttachmentsMixin,
     RenderConfigMixin,
     RenderConfigMixin,
+    WebMercatorMixin,
     ConfigContextModel,
     ConfigContextModel,
     TrackingModelMixin,
     TrackingModelMixin,
     PrimaryModel
     PrimaryModel

+ 28 - 1
netbox/dcim/models/mixins.py

@@ -1,3 +1,4 @@
+import math
 from decimal import Decimal
 from decimal import Decimal
 
 
 from django.apps import apps
 from django.apps import apps
@@ -8,7 +9,13 @@ from django.db import IntegrityError, models, transaction
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
 
 
 from dcim.choices import InterfaceTypeChoices
 from dcim.choices import InterfaceTypeChoices
-from dcim.constants import NONCONNECTABLE_IFACE_TYPES, VIRTUAL_IFACE_TYPES, WIRELESS_IFACE_TYPES
+from dcim.constants import (
+    NONCONNECTABLE_IFACE_TYPES,
+    VIRTUAL_IFACE_TYPES,
+    WEB_MERCATOR_EARTH_RADIUS,
+    WEB_MERCATOR_MAX_LATITUDE,
+    WIRELESS_IFACE_TYPES,
+)
 from netbox.choices import *
 from netbox.choices import *
 from utilities.conversion import (
 from utilities.conversion import (
     DIAMETER_TO_MILLIMETERS,
     DIAMETER_TO_MILLIMETERS,
@@ -26,6 +33,7 @@ __all__ = (
     'InterfaceValidationMixin',
     'InterfaceValidationMixin',
     'MaxFlowMixin',
     'MaxFlowMixin',
     'RenderConfigMixin',
     'RenderConfigMixin',
+    'WebMercatorMixin',
 )
 )
 
 
 
 
@@ -523,3 +531,22 @@ class MaxFlowMixin(models.Model):
         # Validate max_flow and max_flow_unit
         # Validate max_flow and max_flow_unit
         if self.max_flow is not None and not self.max_flow_unit:
         if self.max_flow is not None and not self.max_flow_unit:
             raise ValidationError(_("Must specify a unit when setting a maximum flow"))
             raise ValidationError(_("Must specify a unit when setting a maximum flow"))
+
+
+class WebMercatorMixin:
+    """
+    Provides read-only Web Mercator (EPSG:3857) coordinates calculated from a model's latitude and longitude.
+    """
+    @property
+    def mercator_x(self):
+        if self.latitude is None or self.longitude is None:
+            return None
+        return round(math.radians(float(self.longitude)) * WEB_MERCATOR_EARTH_RADIUS, 2)
+
+    @property
+    def mercator_y(self):
+        if self.latitude is None or self.longitude is None:
+            return None
+        # Web Mercator is undefined at the poles; clamp latitude to the projection's bounds
+        latitude = max(-WEB_MERCATOR_MAX_LATITUDE, min(float(self.latitude), WEB_MERCATOR_MAX_LATITUDE))
+        return round(math.log(math.tan(math.pi / 4 + math.radians(latitude) / 2)) * WEB_MERCATOR_EARTH_RADIUS, 2)

+ 3 - 1
netbox/dcim/models/sites.py

@@ -13,6 +13,8 @@ from dcim.constants import *
 from netbox.models import NestedLtreeGroupModel, PrimaryModel
 from netbox.models import NestedLtreeGroupModel, PrimaryModel
 from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
 from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
 
 
+from .mixins import WebMercatorMixin
+
 __all__ = (
 __all__ = (
     'Location',
     'Location',
     'Region',
     'Region',
@@ -167,7 +169,7 @@ class SiteGroup(ContactsMixin, NestedLtreeGroupModel):
 # Sites
 # Sites
 #
 #
 
 
-class Site(ContactsMixin, ImageAttachmentsMixin, PrimaryModel):
+class Site(ContactsMixin, ImageAttachmentsMixin, WebMercatorMixin, PrimaryModel):
     """
     """
     A Site represents a geographic location within a network; typically a building or campus. The optional facility
     A Site represents a geographic location within a network; typically a building or campus. The optional facility
     field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).
     field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).

+ 38 - 0
netbox/dcim/tests/test_api.py

@@ -458,6 +458,27 @@ class SiteTestCase(APIViewTestCases.APIViewTestCase):
         self.assertNotIn('remove_tags', response.data)
         self.assertNotIn('remove_tags', response.data)
         self.assertIn('tags', response.data)
         self.assertIn('tags', response.data)
 
 
+    def test_web_mercator_coordinates(self):
+        """
+        Web Mercator coordinates are calculated from the GPS coordinates and cannot be written.
+        """
+        obj_perm = ObjectPermission(name='Test permission', actions=['change'])
+        obj_perm.save()
+        obj_perm.users.add(self.user)
+        obj_perm.object_types.add(ObjectType.objects.get_for_model(self.model))
+
+        site = Site.objects.first()
+        data = {
+            'latitude': 40.7128,
+            'longitude': -74.006,
+            'mercator_x': 1,
+            'mercator_y': 1,
+        }
+        response = self.client.patch(self._get_detail_url(site), data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.data['mercator_x'], -8238310.24)
+        self.assertEqual(response.data['mercator_y'], 4970071.58)
+
     def test_remove_tags(self):
     def test_remove_tags(self):
         """
         """
         Remove tags from an existing object via the remove_tags field.
         Remove tags from an existing object via the remove_tags field.
@@ -3090,6 +3111,23 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
 
 
         self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
         self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
 
 
+    def test_web_mercator_coordinates(self):
+        """
+        Web Mercator coordinates are calculated from the GPS coordinates and cannot be written.
+        """
+        self.add_permissions('dcim.change_device')
+        device = Device.objects.first()
+        data = {
+            'latitude': 40.7128,
+            'longitude': -74.006,
+            'mercator_x': 1,
+            'mercator_y': 1,
+        }
+        response = self.client.patch(self._get_detail_url(device), data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.data['mercator_x'], -8238310.24)
+        self.assertEqual(response.data['mercator_y'], 4970071.58)
+
     def test_create_device_replicates_components(self):
     def test_create_device_replicates_components(self):
         """
         """
         Creating a device without specifying replicate_components should instantiate its device type's components.
         Creating a device without specifying replicate_components should instantiate its device type's components.

+ 25 - 0
netbox/dcim/tests/test_models.py

@@ -131,6 +131,31 @@ class MACAddressTestCase(TestCase):
         new_iface.full_clean()  # must not raise
         new_iface.full_clean()  # must not raise
 
 
 
 
+class WebMercatorTestCase(TestCase):
+
+    def test_web_mercator_coordinates(self):
+        for model in (Site, Device):
+            with self.subTest(model=model.__name__):
+                obj = model(latitude=Decimal('40.712800'), longitude=Decimal('-74.006000'))
+                self.assertEqual(obj.mercator_x, -8238310.24)
+                self.assertEqual(obj.mercator_y, 4970071.58)
+
+    def test_web_mercator_coordinates_missing_gps(self):
+        for latitude, longitude in ((None, None), (Decimal('10'), None), (None, Decimal('10'))):
+            site = Site(latitude=latitude, longitude=longitude)
+            self.assertIsNone(site.mercator_x)
+            self.assertIsNone(site.mercator_y)
+
+    def test_web_mercator_coordinates_at_poles(self):
+        site = Site(latitude=Decimal('90'), longitude=Decimal('180'))
+        self.assertEqual(site.mercator_x, 20037508.34)
+        self.assertEqual(site.mercator_y, 20037508.34)
+
+        site = Site(latitude=Decimal('-90'), longitude=Decimal('-180'))
+        self.assertEqual(site.mercator_x, -20037508.34)
+        self.assertEqual(site.mercator_y, -20037508.34)
+
+
 class MACBlockTestCase(TestCase):
 class MACBlockTestCase(TestCase):
 
 
     def test_prefix_normalized(self):
     def test_prefix_normalized(self):

+ 27 - 5
netbox/dcim/ui/panels.py

@@ -37,9 +37,20 @@ class SitePanel(panels.ObjectAttributesPanel):
     facility = attrs.TextAttr('facility')
     facility = attrs.TextAttr('facility')
     description = attrs.TextAttr('description')
     description = attrs.TextAttr('description')
     timezone = attrs.TimezoneAttr('time_zone')
     timezone = attrs.TimezoneAttr('time_zone')
+
+
+class SiteLocationPanel(panels.ObjectAttributesPanel):
+    title = _('Location')
+
     physical_address = attrs.AddressAttr('physical_address', map_url=True, copy_button=True)
     physical_address = attrs.AddressAttr('physical_address', map_url=True, copy_button=True)
     shipping_address = attrs.AddressAttr('shipping_address', map_url=True, copy_button=True)
     shipping_address = attrs.AddressAttr('shipping_address', map_url=True, copy_button=True)
     gps_coordinates = attrs.GPSCoordinatesAttr()
     gps_coordinates = attrs.GPSCoordinatesAttr()
+    mercator_x = attrs.NumericAttr(
+        'mercator_x', label=_('Web Mercator X (EPSG:3857, meters)'), copy_button=True, localize=False
+    )
+    mercator_y = attrs.NumericAttr(
+        'mercator_y', label=_('Web Mercator Y (EPSG:3857, meters)'), copy_button=True, localize=False
+    )
 
 
 
 
 class LocationPanel(panels.NestedGroupObjectPanel):
 class LocationPanel(panels.NestedGroupObjectPanel):
@@ -113,13 +124,8 @@ class RackTypePanel(panels.ObjectAttributesPanel):
 
 
 
 
 class DevicePanel(panels.ObjectAttributesPanel):
 class DevicePanel(panels.ObjectAttributesPanel):
-    region = attrs.NestedObjectAttr('site.region', linkify=True)
-    site = attrs.RelatedObjectAttr('site', linkify=True, grouped_by='group')
-    location = attrs.NestedObjectAttr('location', linkify=True)
-    rack = attrs.TemplatedAttr('rack', template_name='dcim/device/attrs/rack.html')
     virtual_chassis = attrs.RelatedObjectAttr('virtual_chassis', linkify=True)
     virtual_chassis = attrs.RelatedObjectAttr('virtual_chassis', linkify=True)
     parent_device = attrs.TemplatedAttr('parent_bay', template_name='dcim/device/attrs/parent_device.html')
     parent_device = attrs.TemplatedAttr('parent_bay', template_name='dcim/device/attrs/parent_device.html')
-    gps_coordinates = attrs.GPSCoordinatesAttr()
     tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group')
     tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group')
     description = attrs.TextAttr('description')
     description = attrs.TextAttr('description')
     cooling_method = attrs.ChoiceAttr('cooling_method')
     cooling_method = attrs.ChoiceAttr('cooling_method')
@@ -129,6 +135,22 @@ class DevicePanel(panels.ObjectAttributesPanel):
     config_template = attrs.RelatedObjectAttr('config_template', linkify=True)
     config_template = attrs.RelatedObjectAttr('config_template', linkify=True)
 
 
 
 
+class DeviceLocationPanel(panels.ObjectAttributesPanel):
+    title = _('Location')
+
+    region = attrs.NestedObjectAttr('site.region', linkify=True)
+    site = attrs.RelatedObjectAttr('site', linkify=True, grouped_by='group')
+    location = attrs.NestedObjectAttr('location', linkify=True)
+    rack = attrs.TemplatedAttr('rack', template_name='dcim/device/attrs/rack.html')
+    gps_coordinates = attrs.GPSCoordinatesAttr()
+    mercator_x = attrs.NumericAttr(
+        'mercator_x', label=_('Web Mercator X (EPSG:3857, meters)'), copy_button=True, localize=False
+    )
+    mercator_y = attrs.NumericAttr(
+        'mercator_y', label=_('Web Mercator Y (EPSG:3857, meters)'), copy_button=True, localize=False
+    )
+
+
 class DeviceManagementPanel(panels.ObjectAttributesPanel):
 class DeviceManagementPanel(panels.ObjectAttributesPanel):
     title = _('Management')
     title = _('Management')
 
 

+ 2 - 0
netbox/dcim/views.py

@@ -550,6 +550,7 @@ class SiteView(GetRelatedModelsMixin, generic.ObjectView):
     layout = layout.SimpleLayout(
     layout = layout.SimpleLayout(
         left_panels=[
         left_panels=[
             panels.SitePanel(),
             panels.SitePanel(),
+            panels.SiteLocationPanel(),
             CustomFieldsPanel(),
             CustomFieldsPanel(),
             TagsPanel(),
             TagsPanel(),
             CommentsPanel(),
             CommentsPanel(),
@@ -2964,6 +2965,7 @@ class DeviceView(generic.ObjectView):
     layout = layout.SimpleLayout(
     layout = layout.SimpleLayout(
         left_panels=[
         left_panels=[
             panels.DevicePanel(),
             panels.DevicePanel(),
+            panels.DeviceLocationPanel(),
             panels.VirtualChassisMembersPanel(),
             panels.VirtualChassisMembersPanel(),
             CustomFieldsPanel(),
             CustomFieldsPanel(),
             TagsPanel(),
             TagsPanel(),

+ 5 - 5
netbox/netbox/tests/test_search.py

@@ -222,7 +222,7 @@ class SearchBackendTestCase(TestCase):
             # Unnamed devices render as "<manufacturer> <model> (<pk>)"; prefixes display their scope (a site)
             # Unnamed devices render as "<manufacturer> <model> (<pk>)"; prefixes display their scope (a site)
             for site in sites:
             for site in sites:
                 Device.objects.create(site=site, device_type=device_type, role=role, description='Batched')
                 Device.objects.create(site=site, device_type=device_type, role=role, description='Batched')
-                Prefix.objects.create(prefix=f'10.0.{site.pk}.0/24', scope=site, description='Batched')
+                Prefix.objects.create(prefix=f'10.0.{all_sites.index(site)}.0/24', scope=site, description='Batched')
             search_backend.cache(Device.objects.all())
             search_backend.cache(Device.objects.all())
             search_backend.cache(Prefix.objects.all())
             search_backend.cache(Prefix.objects.all())
 
 
@@ -232,15 +232,15 @@ class SearchBackendTestCase(TestCase):
                 rendered = [(result.name, list(result.display_attrs.values())) for result in results]
                 rendered = [(result.name, list(result.display_attrs.values())) for result in results]
             return rendered, len(queries)
             return rendered, len(queries)
 
 
-        sites = list(Site.objects.order_by('name'))
-        rendered, query_count = render_results(sites[:1])
+        all_sites = list(Site.objects.order_by('name'))
+        rendered, query_count = render_results(all_sites[:1])
         self.assertEqual(len(rendered), 2)
         self.assertEqual(len(rendered), 2)
-        rendered, more_query_count = render_results(sites[1:])
+        rendered, more_query_count = render_results(all_sites[1:])
         self.assertEqual(len(rendered), 6)
         self.assertEqual(len(rendered), 6)
         self.assertEqual(more_query_count, query_count)
         self.assertEqual(more_query_count, query_count)
 
 
         self.assertEqual(sum(name.startswith('Manufacturer 1 Device Type 1') for name, _ in rendered), 3)
         self.assertEqual(sum(name.startswith('Manufacturer 1 Device Type 1') for name, _ in rendered), 3)
-        self.assertCountEqual([attrs[0] for name, attrs in rendered if name.startswith('10.0.')], sites)
+        self.assertCountEqual([attrs[0] for name, attrs in rendered if name.startswith('10.0.')], all_sites)
 
 
 
 
 class DeferredCachingTestCase(RQQueueTestMixin, TestCase):
 class DeferredCachingTestCase(RQQueueTestMixin, TestCase):

+ 13 - 0
netbox/netbox/tests/test_ui.py

@@ -4,6 +4,7 @@ from types import SimpleNamespace
 from django.template import Context, Template
 from django.template import Context, Template
 from django.test import RequestFactory, SimpleTestCase, TestCase
 from django.test import RequestFactory, SimpleTestCase, TestCase
 from django.urls import reverse
 from django.urls import reverse
+from django.utils import translation
 from netaddr import IPNetwork
 from netaddr import IPNetwork
 
 
 from account.models import UserToken
 from account.models import UserToken
@@ -313,6 +314,12 @@ class NumericAttrTestCase(TestCase):
         context = attr.get_context(obj, 'speed', 1000, {})
         context = attr.get_context(obj, 'speed', 1000, {})
         self.assertTrue(context['copy_button'])
         self.assertTrue(context['copy_button'])
 
 
+    def test_render_localize(self):
+        obj = SimpleNamespace(x=-8238310.24)
+        with translation.override('de'):
+            self.assertIn('-8238310,24', attrs.NumericAttr('x').render(obj, {'name': 'x'}))
+            self.assertIn('-8238310.24', attrs.NumericAttr('x', localize=False).render(obj, {'name': 'x'}))
+
 
 
 class BooleanAttrTestCase(TestCase):
 class BooleanAttrTestCase(TestCase):
 
 
@@ -745,6 +752,12 @@ class WeightAttrTestCase(SimpleTestCase):
         self.assertIn('10', result)
         self.assertIn('10', result)
         self.assertIn('lbs', result)
         self.assertIn('lbs', result)
 
 
+    def test_render_localized(self):
+        attr = attrs.WeightAttr('weight')
+        obj = self._obj(Decimal('2.5'), 'kg', 2500, 'Kilograms')
+        with translation.override('de'):
+            self.assertIn('2,5', attr.render(obj, self._ctx()))
+
 
 
 class DistanceAttrTestCase(SimpleTestCase):
 class DistanceAttrTestCase(SimpleTestCase):
 
 

+ 4 - 1
netbox/netbox/ui/attrs.py

@@ -169,19 +169,22 @@ class NumericAttr(ObjectAttribute):
     Parameters:
     Parameters:
          unit_accessor (str): Accessor for the unit of measurement to display alongside the value (if any)
          unit_accessor (str): Accessor for the unit of measurement to display alongside the value (if any)
          copy_button (bool): Set to True to include a copy-to-clipboard button
          copy_button (bool): Set to True to include a copy-to-clipboard button
+         localize (bool): Set to False to render the value without locale-specific formatting
     """
     """
     template_name = 'ui/attrs/numeric.html'
     template_name = 'ui/attrs/numeric.html'
 
 
-    def __init__(self, *args, unit_accessor=None, copy_button=False, **kwargs):
+    def __init__(self, *args, unit_accessor=None, copy_button=False, localize=True, **kwargs):
         super().__init__(*args, **kwargs)
         super().__init__(*args, **kwargs)
         self.unit_accessor = unit_accessor
         self.unit_accessor = unit_accessor
         self.copy_button = copy_button
         self.copy_button = copy_button
+        self.localize = localize
 
 
     def get_context(self, obj, attr, value, context):
     def get_context(self, obj, attr, value, context):
         unit = resolve_attr_path(obj, self.unit_accessor) if self.unit_accessor else None
         unit = resolve_attr_path(obj, self.unit_accessor) if self.unit_accessor else None
         return {
         return {
             'unit': unit,
             'unit': unit,
             'copy_button': self.copy_button,
             'copy_button': self.copy_button,
+            'localize': self.localize,
         }
         }
 
 
 
 

+ 2 - 2
netbox/templates/ui/attrs/numeric.html

@@ -1,6 +1,6 @@
-{% load i18n %}
+{% load i18n l10n %}
 <span>
 <span>
-  <span{% if name %} id="attr_{{ name }}"{% endif %}>{{ value }}</span>
+  <span{% if name %} id="attr_{{ name }}"{% endif %}>{% if localize is False %}{{ value|unlocalize }}{% else %}{{ value }}{% endif %}</span>
   {% if unit %}
   {% if unit %}
     {{ unit|lower }}
     {{ unit|lower }}
   {% endif %}
   {% endif %}