You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:实现Forge Viewer点击模型获取GPS坐标的教程或示例代码

Troubleshooting Forge Viewer Geolocation Extension & Example Code

Hey Tom, sorry to hear you're stuck getting the Geolocation Extension working—let's break this down with a concrete, adaptable example that should help you display GPS coordinates when clicking model points.

First, Confirm a Critical Prerequisite

Before jumping into code, make sure your model has geographic metadata attached:

  • If you're using Revit, double-check you set up the project's location (via Manage > Location > Location Settings) and exported the model with this data included.
  • When uploading to Forge, ensure the geographic data is preserved (most common formats like RVT, IFC, or GIS-enabled DWG will retain this info).

Example Custom Extension Code

Here's a full extension that integrates the built-in Geolocation Extension, listens for model clicks, converts viewer coordinates to GPS, and shows them in a simple popup:

class GpsClickExtension extends Autodesk.Viewing.Extension {
    constructor(viewer, options) {
        super(viewer, options);
        this.geolocationExt = null;
        this.popup = null;
    }

    async load() {
        // Load the official Geolocation Extension first
        await this.viewer.loadExtension('Autodesk.Geolocation');
        this.geolocationExt = this.viewer.getExtension('Autodesk.Geolocation');

        // Create a basic popup for displaying coordinates
        this.popup = document.createElement('div');
        this.popup.style.cssText = `
            position: absolute;
            background: #fff;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
            display: none;
            z-index: 1000;
            font-family: system-ui, sans-serif;
            font-size: 14px;
        `;
        document.body.appendChild(this.popup);

        // Listen for model click events
        this.viewer.addEventListener(Autodesk.Viewing.SELECTION_CHANGED_EVENT, this.handleModelClick.bind(this));

        console.log('GpsClickExtension loaded successfully');
        return true;
    }

    handleModelClick(event) {
        // Only process single-point selections
        if (event.selections.length === 0 || event.selections[0].dbIdArray.length !== 1) {
            this.popup.style.display = 'none';
            return;
        }

        const fragId = event.selections[0].fragIdsArray[0];
        // Get the exact clicked point in viewer coordinates
        const hitResult = this.viewer.impl.hitTest(event.clientX, event.clientY, true);
        if (!hitResult || !hitResult.intersectPoint) {
            this.popup.style.display = 'none';
            return;
        }

        const viewerPoint = hitResult.intersectPoint;

        try {
            // Convert viewer coordinates to global model coordinates
            const globalPoint = this.viewer.model.getFragmentList().getWorldMatrix(fragId).transformPoint(viewerPoint);
            // Convert global coordinates to WGS84 GPS (latitude/longitude)
            const gpsCoords = this.geolocationExt.globalToGeographic(globalPoint);

            // Format coordinates for readability
            const lat = gpsCoords.lat.toFixed(6);
            const lon = gpsCoords.lng.toFixed(6);

            // Update and show the popup
            this.popup.innerHTML = `
                <strong>GPS Coordinates:</strong><br>
                Latitude: ${lat}°<br>
                Longitude: ${lon}°
            `;
            this.popup.style.left = `${event.clientX + 15}px`;
            this.popup.style.top = `${event.clientY + 15}px`;
            this.popup.style.display = 'block';
        } catch (err) {
            console.error('Failed to get GPS coordinates:', err);
            this.popup.innerHTML = '<strong>Error:</strong> No geographic data found for this model';
            this.popup.style.display = 'block';
        }
    }

    unload() {
        // Clean up resources
        this.viewer.removeEventListener(Autodesk.Viewing.SELECTION_CHANGED_EVENT, this.handleModelClick.bind(this));
        if (this.popup) {
            document.body.removeChild(this.popup);
            this.popup = null;
        }
        this.geolocationExt = null;
        console.log('GpsClickExtension unloaded');
        return true;
    }
}

// Register the extension for use
Autodesk.Viewing.theExtensionManager.registerExtension('GpsClickExtension', GpsClickExtension);

Key Parts Explained

  • Loading Geolocation: We use await viewer.loadExtension('Autodesk.Geolocation') to ensure the official extension is fully ready before interacting with it.
  • Coordinate Conversion: The globalToGeographic method handles translating model space coordinates to standard WGS84 GPS coordinates (the format used by most mapping tools).
  • Error Handling: The try/catch block catches cases where the model lacks geographic data (a super common gotcha!).
  • Popup UI: This example uses a simple DOM element, but you can swap it out for your preferred component (like a React modal or Bootstrap popup) easily.

How to Implement

  1. Add this code to your project after loading the Forge Viewer script.
  2. When initializing your viewer, load the custom extension:
    viewer.loadExtension('GpsClickExtension');
    
  3. Load a model with geographic data, then click any point—you’ll see the GPS coordinates pop up near your cursor.

Common Fixes for Issues

  • If you see the "No geographic data" error: Double-check your model was exported with location settings enabled (in Revit, confirm you set a shared site location before exporting).
  • If clicks don’t trigger the popup: Ensure you’re using the SELECTION_CHANGED_EVENT correctly, and that the hit test flag (true in hitTest) is enabled for precise point picking.

Hope this gets you up and running smoothly! Let me know if you hit any specific snags.

内容的提问来源于stack exchange,提问作者TD123123123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:47:45