Android平台Google Maps API公共交通耗时及站点查询技术问询
嘿,这俩需求Google Maps的官方API都能完美解决,我给你一步步拆解:
1. 获取两地公共交通(含步行)的耗时
你可以用Google Maps Directions API(Android平台推荐用Maps SDK for Android集成的Directions服务)来实现。当你指定出行模式为TRANSIT时,返回的路线会自动包含步行到站点、换乘步行等环节的时间,直接取路线总耗时即可。
核心实现步骤:
- 先在Google Cloud Console启用Directions API,并确保你的Android应用配置了有效API Key(建议限制包名和SHA-1,避免滥用)。
- 使用Maps SDK的
DirectionsApi发起请求,指定起点、终点和TRANSIT模式:
// 初始化GoogleApiClient(也可结合依赖注入等现代方式实现) val directionsRequest = DirectionsApi.newRequest(googleApiClient) .origin(LatLng(startLatitude, startLongitude)) // 起点坐标 .destination(LatLng(endLatitude, endLongitude)) // 终点坐标 .mode(TravelMode.TRANSIT) // 指定公共交通模式 .await() // 同步请求,也可改用异步回调处理 if (directionsRequest.isSuccess) { // 取第一条最优路线 val firstRoute = directionsRequest.routes.firstOrNull() firstRoute?.legs?.firstOrNull()?.let { leg -> // 获取总耗时,单位为秒 val totalDurationSeconds = leg.duration.inSeconds val totalDurationMinutes = totalDurationSeconds / 60 println("公共交通总耗时:${totalDurationMinutes}分钟") } }
注意:
TRANSIT模式返回的路线已经整合了所有步行环节的时间,不需要额外计算,直接读取leg.duration就是从起点到终点的完整耗时(包括步行到公交站、换乘步行等)。
2. 获取指定位置附近的公共交通站点列表
这个需求可以用Google Places API的Nearby Search功能,通过Maps SDK for Android的Places Client实现,无需依赖设备当前位置,直接指定目标坐标即可。
核心实现步骤:
- 在Google Cloud Console启用Places API,确保API Key配置正确。
- 使用
PlacesClient发起附近搜索请求,指定目标位置、搜索半径和站点类型:
// 创建PlacesClient实例 val placesClient = Places.createClient(context) // 构建附近搜索请求 val nearbySearchRequest = NearbySearchRequest.builder() .location(LatLng(targetLatitude, targetLongitude)) // 指定目标位置坐标 .radius(1000) // 搜索半径,单位为米(可根据需求调整) .type(Place.Type.TRANSIT_STATION) // 搜索所有公共交通站点,也可指定细分类型 // 可选:只想找地铁站用Place.Type.SUBWAY_STATION;公交站用Place.Type.BUS_STATION .build() // 发起异步请求 placesClient.findNearbyPlaces(nearbySearchRequest) .addOnSuccessListener { response -> val transitStations = response.places transitStations.forEach { station -> val stationName = station.name ?: "未知站点" val stationLocation = station.latLng println("找到站点:$stationName,坐标:$stationLocation") } } .addOnFailureListener { exception -> // 处理请求失败情况 println("搜索站点失败:${exception.message}") }
额外提示:
- 可通过调整
radius参数控制搜索范围,最大支持50000米(50公里)。 - 除了
TRANSIT_STATION,还能用更细分的类型筛选特定站点,比如BUS_STATION、SUBWAY_STATION、TRAM_STATION等。
内容的提问来源于stack exchange,提问作者Jan Frait
相关产品推荐
相关产品推荐

