Google Earth 提供 COM API 讓開發者以程式控制 3D 地球引擎。本系列第一篇介紹開發環境建置、參考加入、基本物件模型,並實作最簡單的「啟動 GE、截圖、開啟截圖」Hello World 程式,為後續嵌入、互動、進階控制奠基。
googleearth.exe 可正常執行)EARTHLib,命名空間包含 ApplicationGEClass、FeatureGE 等介面| 類別/介面 | 用途 |
|---|---|
| ApplicationGEClass | GE 應用程式進程控制器,啟動、關閉、截圖、取得視窗控制代碼 |
| GEViewContent | 檢視內容容器,提供 Control、GeRenderHWnd、GeApplication |
| FeatureGE | 地標、圖層、資料夾等地理要素基底介面 |
| PointOnTerrainGE | 地形座標點,含 Longitude、Latitude、Altitude |
using System;
using System.Windows.Forms;
using EARTHLib;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
namespace GEDemo
{
public partial class Form1 : Form
{
private bool _isGeStarted = false;
private ApplicationGEClass _geApp;
public Form1()
{
InitializeComponent();
}
// 啟動/連接 GE
private void btnStart_Click(object sender, EventArgs e) => StartGE();
private void StartGE()
{
if (_isGeStarted) return;
try
{
// 嘗試連接已執行的 GE 實例
_geApp = (ApplicationGEClass)Marshal.GetActiveObject("GoogleEarth.Application");
_isGeStarted = true;
}
catch
{
// 無執行中實例,建立新實例
_geApp = new ApplicationGEClass();
_isGeStarted = true;
}
}
// 截圖儲存
private void btnScreenshot_Click(object sender, EventArgs e)
{
string path = Path.Combine(Application.StartupPath, "ScreenShot.jpg");
try
{
// quality 0-100,數值越高品質越好
_geApp.SaveScreenShot(path, 100);
MessageBox.Show($"截圖已儲存:{path}");
}
catch (Exception ex)
{
MessageBox.Show($"截圖失敗:{ex.Message}");
}
}
// 開啟截圖檔案
private void btnOpenImage_Click(object sender, EventArgs e)
{
string path = Path.Combine(Application.StartupPath, "ScreenShot.jpg");
if (!File.Exists(path))
{
MessageBox.Show("找不到截圖檔案!");
return;
}
Process.Start(path);
}
// 關閉應用程式
private void btnExit_Click(object sender, EventArgs e)
{
Close();
Application.Exit();
}
}
}
googleearth.exe 進程COMException、UnauthorizedAccessException,務必 try-catch點擊「啟動 GE」 → 桌面出現 Google Earth 視窗 → 點擊「截圖」 → 專案目錄產生 ScreenShot.jpg → 點擊「開啟圖片」 → 關聯圖片檢視器開啟。
| 錯誤現象 | 原因 | 解決 |
|---|---|---|
| 找不到 "Google Earth 1.0 Type Library" | 未安裝 GE 或版本不支援 COM | 重新安裝 GE Pro/免費版,確認登錄 HKEY_CLASSES_ROOT\GoogleEarth.Application 存在 |
| GetActiveObject 擲回 COMException (0x800401E3) | 無執行中 GE 實例 | catch 後 new ApplicationGEClass() 建立新實例 |
| SaveScreenShot 無作用/擲回例外 | GE 尚未完成初始化 | 啟動後延遲 1-2 秒或輪詢 IsInitialized() > 0 |
| x64 專案無法載入 EARTHLib | GE COM 為 32 位元 | 專案屬性 → Build → 勾選 "Prefer 32-bit" |
Google Earth COM API 雖功能有限且已停止維護,但對於需要在桌面應用快速整合 3D 地球視覺化的專案,仍具參考價值。現代專案建議評估:
本系列完整原始碼:GEDemo_2009-05-22.rar