首页
学习
活动
专区
圈层
工具
发布

如何在Google Maps for Android上显示路线

在Google Maps for Android上显示路线

基础概念

在Android应用中显示Google Maps路线是指利用Google Maps API在应用程序中绘制从一个地点到另一个地点的导航路径。这通常涉及使用Google Maps Directions API获取路线数据,然后在Google Maps Android SDK中渲染这些路线。

实现方法

1. 准备工作

首先需要:

  • 在Google Cloud Platform中启用Maps SDK for Android和Directions API
  • 获取API密钥
  • 在Android项目中添加Google Maps依赖

2. 实现步骤

添加依赖

在app的build.gradle中添加:

代码语言:txt
复制
implementation 'com.google.android.gms:play-services-maps:18.1.0'
implementation 'com.google.maps.android:android-maps-utils:2.4.0'

显示路线代码示例

代码语言:txt
复制
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    private String apiKey = "YOUR_API_KEY";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        
        // 获取SupportMapFragment并异步获取地图
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        
        // 设置起点和终点
        LatLng origin = new LatLng(37.7749, -122.4194); // 旧金山
        LatLng destination = new LatLng(34.0522, -118.2437); // 洛杉矶
        
        // 在地图上添加标记
        mMap.addMarker(new MarkerOptions().position(origin).title("起点"));
        mMap.addMarker(new MarkerOptions().position(destination).title("终点"));
        
        // 获取并绘制路线
        getDirections(origin, destination);
    }

    private void getDirections(LatLng origin, LatLng destination) {
        new FetchURL(this).execute(
                getUrl(origin, destination, apiKey), 
                "directions");
    }

    private String getUrl(LatLng origin, LatLng dest, String apiKey) {
        // 构建Directions API请求URL
        String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
        String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
        String sensor = "sensor=false";
        String mode = "mode=driving";
        String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
        String output = "json";
        
        return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&key=" + apiKey;
    }

    // 解析JSON响应并绘制路线
    private class FetchURL extends AsyncTask<String, Void, String> {
        private Context mContext;
        
        public FetchURL(Context context) {
            mContext = context;
        }

        @Override
        protected String doInBackground(String... url) {
            String data = "";
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            new ParserTask().execute(result);
        }
    }

    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;
            
            try {
                jObject = new JSONObject(jsonData[0]);
                DirectionsJSONParser parser = new DirectionsJSONParser();
                routes = parser.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points;
            PolylineOptions lineOptions = null;
            
            // 遍历所有路线
            for (int i = 0; i < result.size(); i++) {
                points = new ArrayList<>();
                lineOptions = new PolylineOptions();
                
                // 获取路线上的所有点
                List<HashMap<String, String>> path = result.get(i);
                
                for (int j = 0; j < path.size(); j++) {
                    HashMap<String, String> point = path.get(j);
                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);
                    points.add(position);
                }
                
                // 添加所有点到PolylineOptions
                lineOptions.addAll(points);
                lineOptions.width(10);
                lineOptions.color(Color.BLUE);
                lineOptions.geodesic(true);
            }
            
            // 在地图上绘制折线
            if (lineOptions != null) {
                mMap.addPolyline(lineOptions);
            }
        }
    }
}

DirectionsJSONParser类示例

代码语言:txt
复制
public class DirectionsJSONParser {
    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        
        try {
            jRoutes = jObject.getJSONArray("routes");
            
            // 遍历所有路线
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List<HashMap<String, String>> path = new ArrayList<>();
                
                // 遍历所有路段
                for (int j = 0; j < jLegs.length(); j++) {
                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
                    
                    // 遍历所有步骤
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);
                        
                        // 遍历所有点
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString(list.get(l).latitude));
                            hm.put("lng", Double.toString(list.get(l).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }
    
    // 解码折线点
    private List<LatLng> decodePoly(String encoded) {
        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;
        
        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;
            
            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;
            
            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }
        return poly;
    }
}

优势

  1. 集成简便:Google Maps API提供了完整的解决方案
  2. 功能丰富:支持多种交通方式(驾车、步行、骑行等)
  3. 实时更新:路线会根据实时交通状况进行调整
  4. 全球覆盖:支持全球范围内的路线规划

常见问题及解决方案

1. 地图不显示

  • 原因:API密钥未正确配置或未启用相关API
  • 解决:检查API密钥,确保已启用Maps SDK for Android和Directions API

2. 路线不显示

  • 原因:网络请求失败或JSON解析错误
  • 解决:检查网络权限,验证JSON解析逻辑

3. 性能问题

  • 原因:路线过于复杂或未优化绘制
  • 解决:简化路线点数量,使用PolylineOptions优化绘制

4. 超出配额

  • 原因:API调用次数超过免费配额
  • 解决:升级API配额或优化应用减少调用次数

应用场景

  1. 导航应用
  2. 物流和配送系统
  3. 旅行规划应用
  4. 共享出行服务
  5. 位置追踪应用

注意事项

  1. 确保遵守Google Maps API的使用条款
  2. 注意API调用配额限制
  3. 考虑使用缓存减少API调用
  4. 处理网络不可用的情况
  5. 在AndroidManifest.xml中添加必要的权限
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的文章

领券