Android-在Google地图上显示方向

tamuzi_s

如以下屏幕截图所示,如何获取并在Google地图上显示方向?截屏

克里希纳(Krishna Avadhanam)

尝试此代码,您需要google api传递密钥才能访问该密钥的开发人员尝试此代码可正常工作。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class PathGoogleMapActivity extends FragmentActivity {

    private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,
            -73.998585);
    private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);
    private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094);

    GoogleMap googleMap;
    final String TAG = "PathGoogleMapActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_path_google_map);
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        googleMap = fm.getMap();

        MarkerOptions options = new MarkerOptions();
        options.position(LOWER_MANHATTAN);
        options.position(BROOKLYN_BRIDGE);
        options.position(WALL_STREET);
        googleMap.addMarker(options);
        String url = getMapsApiDirectionsUrl();
        ReadTask downloadTask = new ReadTask();
        downloadTask.execute(url);

        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(BROOKLYN_BRIDGE,
                13));
        addMarkers();

    }

    private String getMapsApiDirectionsUrl() {
        String waypoints = "waypoints=optimize:true|"
                + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude
                + "|" + "|" + BROOKLYN_BRIDGE.latitude + ","
                + BROOKLYN_BRIDGE.longitude + "|" + WALL_STREET.latitude + ","
                + WALL_STREET.longitude;

        String sensor = "sensor=false";
        String params = waypoints + "&" + sensor;
        String output = "json";
        String url = "https://maps.googleapis.com/maps/api/directions/"
                + output + "?" + params;
        return url;
    }

    private void addMarkers() {
        if (googleMap != null) {
            googleMap.addMarker(new MarkerOptions().position(BROOKLYN_BRIDGE)
                    .title("First Point"));
            googleMap.addMarker(new MarkerOptions().position(LOWER_MANHATTAN)
                    .title("Second Point"));
            googleMap.addMarker(new MarkerOptions().position(WALL_STREET)
                    .title("Third Point"));
        }
    }

    private class ReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... url) {
            String data = "";
            try {
                HttpConnection http = new HttpConnection();
                data = http.readUrl(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]);
                PathJSONParser parser = new PathJSONParser();
                routes = parser.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
            ArrayList<LatLng> points = null;
            PolylineOptions polyLineOptions = null;

            // traversing through routes
            for (int i = 0; i < routes.size(); i++) {
                points = new ArrayList<LatLng>();
                polyLineOptions = new PolylineOptions();
                List<HashMap<String, String>> path = routes.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.addAll(points);
                polyLineOptions.width(2);
                polyLineOptions.color(Color.BLUE);
            }

            googleMap.addPolyline(polyLineOptions);
        }
    }
}

为了获取绘制路径的说明,我使用了Google Directions API。我们只是使用HTTP请求命中给定的URL并获得json响应。此Google服务会计算给定位置之间的方向。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

public class HttpConnection {
    public String readUrl(String mapsApiDirectionsUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(mapsApiDirectionsUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    iStream));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            data = sb.toString();
            br.close();
        } catch (Exception e) {
            Log.d("Exception while reading url", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

}

最后一堂课jasonparser会为您指明方向

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.model.LatLng;

public class PathJSONParser {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;
        try {
            jRoutes = jObject.getJSONArray("routes");
            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {
                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps
                                .get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat",
                                    Double.toString(((LatLng) list.get(l)).latitude));
                            hm.put("lng",
                                    Double.toString(((LatLng) list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }
        return routes;
    }

    /**
     * Method Courtesy :
     * jeffreysambells.com/2010/05/27
     * /decoding-polylines-from-google-maps-direction-api-with-java
     * */
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<LatLng>();
        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;
    }
}

xmal和manifestfiles在下面

activity_path_google_map.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TaskRoadMap" >

   <fragment
        android:id="@+id/map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        class="com.google.android.gms.maps.SupportMapFragment"/>

</RelativeLayout>

您的清单文件具有权限

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javapapers.android.maps.path"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <permission
        android:name="com.javapapers.android.maps.path.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.javapapers.android.maps.path.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.javapapers.android.maps.path.PathGoogleMapActivity"
            android:label="@string/title_activity_path_google_map" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyARCTcX8bABCDE_ohscNcALAak-HnjTO5s" />

        <meta-data 
            android:name="com.google.android.gms.version" 
            android:value="@integer/google_play_services_version" />

    </application>

</manifest>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在Android的Google地图上显示textview

来自分类Dev

Android如何在Google地图上指出Qibla方向

来自分类Dev

如何在Android的Google地图上显示涟漪动画?

来自分类Dev

如何在Android的Google地图上显示可用的Wifi热点?

来自分类Dev

如何在Android Studio的Google地图上显示图像

来自分类Dev

Android在esri地图上显示多点

来自分类Dev

无法在地图上显示路线ArcGIS Android

来自分类Dev

Android在esri地图上显示多点

来自分类Dev

Android-Google Map-如何在地图上显示多个标记?

来自分类Dev

如何在Android棉花糖上的Google地图上显示当前位置?

来自分类Dev

Android中的Google地图能否显示指南针方向;如果是这样,怎么办?

来自分类Dev

搜索位置(城市名称),在地图上显示(Android)

来自分类Dev

KML 点无法在 Android 谷歌地图上显示

来自分类Dev

防止Android中的Google地图上的标记旋转

来自分类Dev

在Android Google地图上缩放时的错误行为

来自分类Dev

在Android的Google地图上获取位置触摸的坐标

来自分类Dev

在Android的Google地图上获取位置触摸的坐标

来自分类Dev

如何在Android的Google地图上绘制自由手形

来自分类Dev

Android上的Google地图显示灰屏

来自分类Dev

Android的Web视图不显示Google地图

来自分类Dev

Google地图在Android中无法突然显示

来自分类Dev

在Android的Google地图中显示位置

来自分类Dev

Android:Google地图未显示在屏幕上

来自分类Dev

如何在Android中的谷歌地图上的圆形图像上显示图像

来自分类Dev

在给定半径内在地图上显示标记(Xamarin.Android)

来自分类Dev

如何在地图上显示图钉的纬度和经度(Android Studio)

来自分类Dev

在 Android 平台的谷歌地图上始终显示标记标签和默认图钉图标

来自分类Dev

如何使用 GeoFirestore (Java/Android) 在谷歌地图上显示多个标记?

来自分类Dev

在Google地图上显示当前位置

Related 相关文章

  1. 1

    在Android的Google地图上显示textview

  2. 2

    Android如何在Google地图上指出Qibla方向

  3. 3

    如何在Android的Google地图上显示涟漪动画?

  4. 4

    如何在Android的Google地图上显示可用的Wifi热点?

  5. 5

    如何在Android Studio的Google地图上显示图像

  6. 6

    Android在esri地图上显示多点

  7. 7

    无法在地图上显示路线ArcGIS Android

  8. 8

    Android在esri地图上显示多点

  9. 9

    Android-Google Map-如何在地图上显示多个标记?

  10. 10

    如何在Android棉花糖上的Google地图上显示当前位置?

  11. 11

    Android中的Google地图能否显示指南针方向;如果是这样,怎么办?

  12. 12

    搜索位置(城市名称),在地图上显示(Android)

  13. 13

    KML 点无法在 Android 谷歌地图上显示

  14. 14

    防止Android中的Google地图上的标记旋转

  15. 15

    在Android Google地图上缩放时的错误行为

  16. 16

    在Android的Google地图上获取位置触摸的坐标

  17. 17

    在Android的Google地图上获取位置触摸的坐标

  18. 18

    如何在Android的Google地图上绘制自由手形

  19. 19

    Android上的Google地图显示灰屏

  20. 20

    Android的Web视图不显示Google地图

  21. 21

    Google地图在Android中无法突然显示

  22. 22

    在Android的Google地图中显示位置

  23. 23

    Android:Google地图未显示在屏幕上

  24. 24

    如何在Android中的谷歌地图上的圆形图像上显示图像

  25. 25

    在给定半径内在地图上显示标记(Xamarin.Android)

  26. 26

    如何在地图上显示图钉的纬度和经度(Android Studio)

  27. 27

    在 Android 平台的谷歌地图上始终显示标记标签和默认图钉图标

  28. 28

    如何使用 GeoFirestore (Java/Android) 在谷歌地图上显示多个标记?

  29. 29

    在Google地图上显示当前位置

热门标签

归档