AndroidStudio(Java)中使用地图方向API在两点之间找到路线
创始人
2024-08-21 11:30:16
0
  1. build.gradle 文件中添加如下代码:
    implementation 'com.google.maps:google-maps-services:0.5.0'
  1. AndroidManifest.xml 文件中添加地图 API 密钥:

  1. MainActivity.java 文件中添加如下代码:
import com.google.maps.DirectionsApi;
import com.google.maps.DirectionsApiRequest;
import com.google.maps.GeoApiContext;
import com.google.maps.model.DirectionsResult;
import com.google.maps.model.TravelMode;

public class MainActivity extends AppCompatActivity {

    private GeoApiContext mGeoApiContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化 GeoApiContext,需要传入地图 API 密钥
        mGeoApiContext = new GeoApiContext.Builder()
                .apiKey("YOUR_API_KEY")
                .build();

        // 调用查询路线的方法
        getDirections();
    }

    private void getDirections() {
        DirectionsApiRequest request = DirectionsApi.getDirections(mGeoApiContext,
                "originAddress",
                "destinationAddress")
                .mode(TravelMode.DRIVING);

        try {
            DirectionsResult result = request.await();
            // 获取路线信息
            // Code your logic for obtaining and displaying the route here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意替换 YOUR_API_KEYoriginAddressdestinationAddress。 4. 解析查询结果并在地图上显示路线。 这里展示一个简单的方法:使用 Polyline 在地图上显示路线

PolylineOptions line = new PolylineOptions();
List latLngList = new ArrayList();

List decodedPath = result.routes[0].overviewPolyline.decodePath();
for (com.google.maps.model.LatLng latLng : decodedPath) {
    latLngList.add(new LatLng(latLng.lat, latLng.lng));
}

line.addAll(latLngList);
line.width(12f);
line.color(Color.RED);

// 在地图上画出路线
map.addPolyline(line);

注:这里的 map 是指 GoogleMap 对象,需要先获得该对象(示例略)。

相关内容

热门资讯

日前!红龙poker作必弊指令... 日前!红龙poker作必弊指令(透视)海豹大厅超级三加一辅助(其实是有辅助软件)-哔哩哔哩1、玩家可...
网友热议!约局吧德州有挂吗(透... 网友热议!约局吧德州有挂吗(透视)红人阁自动挂机脚本(确实是真的辅助软件)-哔哩哔哩1、操作简单,无...
透视辅助!破解辅助插件wepo... 透视辅助!破解辅助插件wepoker(透视)开心十三张脚本(原来有辅助app)-哔哩哔哩开心十三张脚...
于此同时!wepoker俱乐部... 于此同时!wepoker俱乐部辅助器(透视)圣盛荆州晃晃三五七辅助(总是有辅助软件)-哔哩哔哩1、下...
透视神器!pokermaste... 透视神器!pokermaster破解版(透视)多乐小程序游戏辅助器(确实真的是有辅助软件)-哔哩哔哩...
据统计!aapoker怎么拿好... 据统计!aapoker怎么拿好牌(透视)九江讨赏辅助(本来是真的辅助工具)-哔哩哔哩该软件可以轻松地...
日前!wepoker辅助器有哪... 日前!wepoker辅助器有哪些功能(透视)微信小程序怎么开挂(一贯是真的辅助软件)-哔哩哔哩1、微...
随着!aapoker怎么设置抽... 随着!aapoker怎么设置抽水(透视)蜜瓜大厅辅助免费下载(本来有辅助辅助器)-哔哩哔哩1、玩家可...
据悉!wepoker破解器有用... 据悉!wepoker破解器有用吗(透视)来物局怎么开挂(竟然有辅助辅助器)-哔哩哔哩1、游戏颠覆性的...
辅助透视!wepoker辅助软... 辅助透视!wepoker辅助软件价格(透视)爱来大菠萝有挂吗(总是是有辅助插件)-哔哩哔哩1、首先打...