Telegram Bot API sendLocation 使用教程
ScreenShot_2025-12-21_133940_406.jpg
## 1. sendLocation 方法用途介绍

sendLocation 是 Telegram Bot API 提供的一个核心方法,用于向指定聊天发送地理位置信息。

**主要用途:**
- 向用户、群组或频道发送地理位置坐标
- 可设置实时位置更新和位置有效期
- 实现位置共享、导航指引和地理信息展示功能

**核心特点:**
- 支持发送静态地理位置坐标
- 支持发送实时位置更新(Live Location)
- 可设置位置有效期(1-86400秒)
- 可设置位置精度、标题、水平精度因子(HDOP)等高级参数
- 支持回复到聊天中的特定消息
- 可选择禁用通知
- 支持发送到 Direct Messages 聊天主题

## 2. 原生 PHP 调用实例

### 2.1 准备工作

确保你的 PHP 环境满足以下要求:
- PHP 5.6 或更高版本
- 已安装 cURL 扩展
- 已创建 Telegram Bot 并获取 Bot Token

### 2.2 发送基本地理位置
```php
<?php
/**
 * 使用 Telegram Bot API 发送基本地理位置
 * @param string $botToken Bot Token
 * @param int|string $chatId 聊天 ID
 * @param float $latitude 纬度
 * @param float $longitude 经度
 * @return array 响应结果
 */
function sendBasicLocation($botToken, $chatId, $latitude, $longitude) {
    $url = "https://api.telegram.org/bot{$botToken}/sendLocation";
    
    $data = [
        'chat_id' => $chatId,
        'latitude' => $latitude,
        'longitude' => $longitude
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

// 使用示例
$botToken = "YOUR_BOT_TOKEN";
$chatId = 123456789; // 用户或群组的聊天 ID
$latitude = 39.9042; // 北京纬度
$longitude = 116.4074; // 北京经度

$result = sendBasicLocation($botToken, $chatId, $latitude, $longitude);

if ($result['ok']) {
    echo "地理位置发送成功!消息 ID: " . $result['result']['message_id'];
} else {
    echo "发送失败:" . $result['description'];
}
?>
```

### 2.3 发送带高级选项的地理位置

```php
<?php
/**
 * 使用 Telegram Bot API 发送带高级选项的地理位置
 * @param string $botToken Bot Token
 * @param int|string $chatId 聊天 ID
 * @param float $latitude 纬度
 * @param float $longitude 经度
 * @param array $options 高级选项
 * @return array 响应结果
 */
function sendAdvancedLocation($botToken, $chatId, $latitude, $longitude, $options = []) {
    $url = "https://api.telegram.org/bot{$botToken}/sendLocation";
    
    $data = [
        'chat_id' => $chatId,
        'latitude' => $latitude,
        'longitude' => $longitude
    ];
    
    // 合并高级选项
    $allowedOptions = [
        'horizontal_accuracy', 'live_period', 'heading', 'proximity_alert_radius',
        'disable_notification', 'protect_content', 'reply_to_message_id',
        'allow_sending_without_reply', 'reply_markup', 'direct_messages_topic_id',
        'suggested_post_parameters'
    ];
    
    foreach ($allowedOptions as $option) {
        if (isset($options[$option])) {
            $data[$option] = $options[$option];
        }
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

// 使用示例 - 发送实时位置
$botToken = "YOUR_BOT_TOKEN";
$chatId = 123456789;
$latitude = 39.9042;
$longitude = 116.4074;

$result = sendAdvancedLocation(
    $botToken,
    $chatId,
    $latitude,
    $longitude,
    [
        'live_period' => 3600, // 实时位置有效期(秒)
        'horizontal_accuracy' => 50, // 位置精度(米)
        'heading' => 90, // 方向(度)
        'proximity_alert_radius' => 100, // 接近提醒半径(米)
        'disable_notification' => false,
        'direct_messages_topic_id' => 67890 // Direct Messages 聊天主题 ID
    ]
);

if ($result['ok']) {
    echo "高级地理位置发送成功!";
} else {
    echo "发送失败:" . $result['description'];
}
?>
```

### 2.4 完整的 Telegram Bot 地理位置发送类

```php
<?php
class TelegramLocationBot {
    private $botToken;
    
    /**
     * 构造函数
     * @param string $botToken Bot Token
     */
    public function __construct($botToken) {
        $this->botToken = $botToken;
    }
    
    /**
     * 发送基本地理位置
     * @param int|string $chatId 聊天 ID
     * @param float $latitude 纬度
     * @param float $longitude 经度
     * @return array 响应结果
     */
    public function sendLocation($chatId, $latitude, $longitude) {
        return $this->sendAdvancedLocation($chatId, $latitude, $longitude, []);
    }
    
    /**
     * 发送实时位置
     * @param int|string $chatId 聊天 ID
     * @param float $latitude 纬度
     * @param float $longitude 经度
     * @param int $livePeriod 实时位置有效期(秒)
     * @param array $options 其他选项
     * @return array 响应结果
     */
    public function sendLiveLocation($chatId, $latitude, $longitude, $livePeriod = 3600, $options = []) {
        $params = $options;
        $params['live_period'] = $livePeriod;
        
        return $this->sendAdvancedLocation($chatId, $latitude, $longitude, $params);
    }
    
    /**
     * 发送带高级选项的地理位置
     * @param int|string $chatId 聊天 ID
     * @param float $latitude 纬度
     * @param float $longitude 经度
     * @param array $options 高级选项
     * @return array 响应结果
     */
    public function sendAdvancedLocation($chatId, $latitude, $longitude, $options = []) {
        $url = "https://api.telegram.org/bot{$this->botToken}/sendLocation";
        
        $data = [
            'chat_id' => $chatId,
            'latitude' => $latitude,
            'longitude' => $longitude
        ];
        
        // 验证坐标有效性
        if ($latitude < -90 || $latitude > 90) {
            return [
                'ok' => false,
                'error_code' => 400,
                'description' => 'Invalid latitude value. Must be between -90 and 90.'
            ];
        }
        
        if ($longitude < -180 || $longitude > 180) {
            return [
                'ok' => false,
                'error_code' => 400,
                'description' => 'Invalid longitude value. Must be between -180 and 180.'
            ];
        }
        
        // 合并高级选项
        $allowedOptions = [
            'horizontal_accuracy', 'live_period', 'heading', 'proximity_alert_radius',
            'disable_notification', 'protect_content', 'reply_to_message_id',
            'allow_sending_without_reply', 'reply_markup', 'direct_messages_topic_id',
            'suggested_post_parameters'
        ];
        
        foreach ($allowedOptions as $option) {
            if (isset($options[$option])) {
                $data[$option] = $options[$option];
            }
        }
        
        return $this->sendRequest($url, $data);
    }
    
    /**
     * 编辑实时位置
     * @param int|string $chatId 聊天 ID
     * @param int $messageId 消息 ID
     * @param float $latitude 纬度
     * @param float $longitude 经度
     * @param array $options 选项
     * @return array 响应结果
     */
    public function editLiveLocation($chatId, $messageId, $latitude, $longitude, $options = []) {
        $url = "https://api.telegram.org/bot{$this->botToken}/editMessageLiveLocation";
        
        $data = [
            'chat_id' => $chatId,
            'message_id' => $messageId,
            'latitude' => $latitude,
            'longitude' => $longitude
        ];
        
        // 合并选项
        $allowedOptions = [
            'horizontal_accuracy', 'heading', 'proximity_alert_radius', 'reply_markup'
        ];
        
        foreach ($allowedOptions as $option) {
            if (isset($options[$option])) {
                $data[$option] = $options[$option];
            }
        }
        
        return $this->sendRequest($url, $data);
    }
    
    /**
     * 停止实时位置更新
     * @param int|string $chatId 聊天 ID
     * @param int $messageId 消息 ID
     * @param array $options 选项
     * @return array 响应结果
     */
    public function stopLiveLocation($chatId, $messageId, $options = []) {
        $url = "https://api.telegram.org/bot{$this->botToken}/stopMessageLiveLocation";
        
        $data = [
            'chat_id' => $chatId,
            'message_id' => $messageId
        ];
        
        // 合并选项
        if (isset($options['reply_markup'])) {
            $data['reply_markup'] = $options['reply_markup'];
        }
        
        return $this->sendRequest($url, $data);
    }
    
    /**
     * 发送 HTTP 请求
     * @param string $url 请求 URL
     * @param array $data 请求数据
     * @return array 响应结果
     */
    private function sendRequest($url, $data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            return [
                'ok' => false,
                'error_code' => $httpCode,
                'description' => 'cURL 错误: ' . $error
            ];
        }
        
        curl_close($ch);
        return json_decode($response, true);
    }
    
    /**
     * 获取更新
     * @param int|null $offset 更新偏移量
     * @param int|null $limit 更新数量
     * @return array 响应结果
     */
    public function getUpdates($offset = null, $limit = null) {
        $url = "https://api.telegram.org/bot{$this->botToken}/getUpdates";
        
        $data = [];
        if ($offset !== null) $data['offset'] = $offset;
        if ($limit !== null) $data['limit'] = $limit;
        
        return $this->sendRequest($url, $data);
    }
}

// 使用示例
$botToken = "YOUR_BOT_TOKEN";
$bot = new TelegramLocationBot($botToken);
$chatId = 123456789;

// 发送基本地理位置
echo "发送基本地理位置...\n";
$result1 = $bot->sendLocation($chatId, 39.9042, 116.4074);
if ($result1['ok']) {
    echo "基本地理位置发送成功!消息 ID: " . $result1['result']['message_id'] . "\n";
} else {
    echo "发送失败:" . $result1['description'] . "\n";
}

// 发送实时地理位置
echo "\n发送实时地理位置...\n";
$result2 = $bot->sendLiveLocation(
    $chatId,
    39.9042, 
    116.4074,
    1800, // 30分钟有效期
    [
        'horizontal_accuracy' => 100, // 位置精度100米
        'heading' => 45, // 方向45度
        'proximity_alert_radius' => 200 // 接近提醒半径200米
    ]
);

if ($result2['ok']) {
    echo "实时地理位置发送成功!消息 ID: " . $result2['result']['message_id'] . "\n";
} else {
    echo "发送失败:" . $result2['description'] . "\n";
}

// 编辑实时地理位置(模拟位置移动)
echo "\n编辑实时地理位置...\n";
if ($result2['ok']) {
    $messageId = $result2['result']['message_id'];
    $result3 = $bot->editLiveLocation(
        $chatId,
        $messageId,
        39.9052, // 新纬度
        116.4084, // 新经度
        [
            'heading' => 90, // 更新方向
            'horizontal_accuracy' => 50 // 提高精度
        ]
    );
    
    if ($result3['ok']) {
        echo "实时地理位置更新成功!\n";
    } else {
        echo "更新失败:" . $result3['description'] . "\n";
    }
}

// 停止实时地理位置更新
echo "\n停止实时地理位置更新...\n";
if ($result2['ok']) {
    $messageId = $result2['result']['message_id'];
    $result4 = $bot->stopLiveLocation($chatId, $messageId);
    
    if ($result4['ok']) {
        echo "实时地理位置更新已停止!\n";
    } else {
        echo "停止失败:" . $result4['description'] . "\n";
    }
}
?>
```




2.5 注意事项

1. **坐标要求:**
   - 纬度(latitude)范围:-90 到 90
   - 经度(longitude)范围:-180 到 180
   - 精度建议:至少保留6位小数以确保准确性

2. **实时位置参数:**
   - `live_period`:实时位置有效期,范围1-86400秒(1天)
   - `horizontal_accuracy`:位置精度,范围1-1500米
   - `heading`:方向,范围0-359度(0度为北,顺时针方向)
   - `proximity_alert_radius`:接近提醒半径,范围1-100000米

3. **聊天 ID 格式:**
   - 私人聊天 ID 是整数
   - 群组和频道 ID 通常以 `-100` 开头的负数

4. **高级选项:**
   - `direct_messages_topic_id` 用于将位置发送到 Direct Messages 聊天主题
   - `protect_content` 可防止位置被转发或保存

## 3. 应用场景

- **位置共享:** 分享聚会地点、活动位置等
- **导航指引:** 发送目的地坐标,提供导航指引
- **实时追踪:** 发送实时位置更新,实现人员或物体追踪
- **地理信息展示:** 展示兴趣点、商家位置等
- **服务配送:** 显示配送员实时位置,提供物流追踪

## 4. 运行指南

1. 将以上代码保存为 `.php` 文件
2. 替换 `YOUR_BOT_TOKEN` 为你的实际 Bot Token
3. 替换聊天 ID 和坐标为实际值
4. 在命令行或浏览器中运行 PHP 文件

```bash
php telegram-send-location.php

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部