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

如何在MAUI应用中使用Google Directions API?密钥、付费及实现咨询

在MAUI中使用Google Maps Route/Direction APIs的实现指南

1. API密钥复用问题

可以复用你在Google Cloud控制台创建的同一API密钥,只需确保该密钥已启用Maps JavaScript API和Directions API权限,同时设置好合适的限制(如安卓包名+SHA-1指纹、iOS Bundle ID),避免密钥被滥用。

2. 服务付费情况

Google Maps Directions API是付费服务,属于Google Maps Platform计费体系。费用根据调用次数、请求复杂度等计算,超出免费额度后按阶梯费率收取,建议提前确认Google Cloud定价规则。

3. MAUI中实现最短路径展示的步骤

准备工作

  • 确认Google Cloud项目已启用Directions API和对应地图服务API(如Web端的Maps JavaScript API,或移动端的Maps SDK)。
  • 配置API密钥的应用限制:针对MAUI安卓端添加包名与SHA-1指纹,iOS端添加Bundle ID。

方案一:WebView加载Google Maps(快速实现)

  1. 在MAUI项目中添加WebView控件,加载包含Google Maps的本地HTML文件。
  2. 编写HTML代码调用Directions API获取最短路径(默认返回最短路径):
<!DOCTYPE html>
<html>
<head>
    <script src="https://maps.googleapis.com/maps/api/js?key=你的API密钥"></script>
    <script>
        function initMap() {
            const directionsService = new google.maps.DirectionsService();
            const directionsRenderer = new google.maps.DirectionsRenderer();
            const map = new google.maps.Map(document.getElementById('map'), {
                zoom: 14,
                center: {lat: 37.7749, lng: -122.4194} // 初始地图中心点
            });
            directionsRenderer.setMap(map);
            calculateRoute(directionsService, directionsRenderer);
        }

        function calculateRoute(service, renderer) {
            service.route({
                origin: '起点地址/经纬度',
                destination: '终点地址/经纬度',
                travelMode: 'DRIVING', // 可选DRIVING/WALKING/BICYCLING/TRANSIT
                avoidHighways: false,
                avoidTolls: false
            }, (response, status) => {
                if (status === 'OK') {
                    renderer.setDirections(response);
                } else {
                    alert('路径查询失败: ' + status);
                }
            });
        }
    </script>
</head>
<body onload="initMap()">
    <div id="map" style="height: 100%; width: 100%;"></div>
</body>
</html>
  1. 在MAUI的XAML中引用该HTML文件(需将HTML设为复制到输出目录的资源):
<WebView Source="map.html" HorizontalOptions="Fill" VerticalOptions="Fill"/>

方案二:第三方MAUI地图库(原生体验)

使用如Plugin.Maui.Maps这类库实现原生地图集成:

  1. 安装对应NuGet包。
  2. 配置平台API密钥:
    • 安卓:在AndroidManifest.xml添加:
      <meta-data android:name="com.google.android.geo.API_KEY" android:value="你的API密钥"/>
      
    • iOS:在Info.plist添加:
      <key>GoogleMapsAPIKey</key>
      <string>你的API密钥</string>
      
  3. 通过库的API调用Directions接口获取路径数据,再在地图上绘制路径折线。

自定义路径样式

如果需要自定义路径外观,可解析Directions API返回的经纬度点集合,手动在地图上绘制折线并设置颜色、宽度等属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:35:08