无法在Google Map中绘制路线

时间:2019-03-20 17:28:06

标签: java android kotlin

我试图绘制一条从起点到目的地的路线,但所得到的只是在没有任何路线连接的位置上的标记

这是我所拥有的照片

here is a picture of what I have

请联系我的位置信息 下面是我的代码:

MapActivity:

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap

    private val LOWER_MANHATTAN = LatLng(
        40.722543,
        -73.998585
    )
    private val BROOKLYN_BRIDGE = LatLng(40.7057, -73.9964)
    private val WALL_STREET = LatLng(40.7064, -74.0094)

    val TAG = "PathGoogleMapActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)


    }

    private fun addMarkers() {
        if (mMap != null){
            mMap.addMarker(MarkerOptions().position(BROOKLYN_BRIDGE)
                .title("First point"))
            mMap.addMarker(MarkerOptions().position(LOWER_MANHATTAN)
                .title("Second point"))
            mMap.addMarker(MarkerOptions().position(WALL_STREET)
                .title("Third point"))
        }
    }

/*    fun getMapsApiDirectionsUrl(): String{
        val waypoints = ("waypoints=optimize:true|"
                + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude
                + "|" + "|" + BROOKLYN_BRIDGE.latitude + ","
                + BROOKLYN_BRIDGE.longitude + "|" + WALL_STREET.latitude + ","
                + WALL_STREET.longitude)

        val sensor = "sensor=false"
        val params = "$waypoints&$sensor"
        val output = "json"
        return ("https://maps.googleapis.com/maps/api/directions/"
                + output + "?" + params)
    }*/



    private fun getMapsApiDirectionsUrl(): String {
        val waypoints = ("waypoints=optimize:true|"
                + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude
                + "|" + "|" + WALL_STREET.latitude + ","
                + WALL_STREET.longitude)
        val OriDest =
            "origin=" + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude + "&destination=" + WALL_STREET.latitude + "," + WALL_STREET.longitude

        val sensor = "sensor=false"
        val params = "$OriDest&%20$waypoints&$sensor"
        val output = "json"
        return ("https://maps.googleapis.com/maps/api/directions/"
                + output + "?" + params)
    }
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

 // Add a marker in Sydney and move the camera
         val sydney = LatLng(-34.0, 151.0)
         mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
         mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))


        val options = MarkerOptions()
        options.position(LOWER_MANHATTAN)
        options.position(BROOKLYN_BRIDGE)
        options.position(WALL_STREET)
        mMap.addMarker(options)

        val url = getMapsApiDirectionsUrl()
        val downloadTask = ReadTask(this)
        downloadTask.execute(url)

        mMap.moveCamera(
            CameraUpdateFactory.newLatLngZoom(
                BROOKLYN_BRIDGE,
                13f
            )
        )
        addMarkers()
    }

    private class ReadTask(mapsActivity: MapsActivity) : AsyncTask<String,Void,String>(){
        private val activityReference: WeakReference<MapsActivity> = WeakReference(mapsActivity)

        override fun doInBackground(vararg p0: String?): String {
            var data = ""
            try {
                val http = HttpConnection()
                data = http.readUrl(p0[0])
            } catch (e: Exception) {
                Log.d("Background Task", e.toString())
            }

            return data
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            val activity = activityReference.get()
            if (activity == null || activity.isFinishing) return

            ParserTask(activity).execute(result)
        }

    }

    private class ParserTask(context: MapsActivity) : AsyncTask<String,Int, List<List<HashMap<String,String>>>>() {
        private val activityReference: WeakReference<MapsActivity> = WeakReference(context)
        override fun doInBackground(vararg p0: String?): List<List<HashMap<String, String>>> {
            val jObject: JSONObject
            var routes: List<List<HashMap<String, String>>>? = null

            try {
                jObject = JSONObject(p0[0])
                val parser = PathJSONParser()
                routes = parser.parse(jObject)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return routes!!
        }

        override fun onPostExecute(routes: List<List<HashMap<String, String>>>?) {
            super.onPostExecute(routes)
            val activity = activityReference.get()
            if (activity == null || activity.isFinishing) return
            try {
                var points: ArrayList<LatLng>
                var polyLineOptions: PolylineOptions? = null
                // traversing through routes
                for (i in 0 until routes!!.size) {
                    points = ArrayList()
                    polyLineOptions = PolylineOptions()
                    val path = routes[i]

                    for (j in path.indices) {
                        val point = path[j]

                        val lat = java.lang.Double.parseDouble(point["lat"]!!)
                        val lng = java.lang.Double.parseDouble(point["lng"]!!)
                        val position = LatLng(lat, lng)

                        points.add(position)
                    }

                    polyLineOptions.addAll(points)
                    polyLineOptions.width(2f)
                    polyLineOptions.color(Color.BLUE)
                }
                activity.mMap.addPolyline(polyLineOptions)
            } catch (e: Exception) {
            }
        }
    }

}

PathJSONParser类:

public class PathJSONParser {

    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");
            /* 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<>();

                /* 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(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 ignored) {
        }
        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<>();
        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 个答案:

答案 0 :(得分:0)

我终于得到了所需的解决方案: 首先要知道从Google获得的API密钥是绘制您的路线的密钥。 所以:

 private fun getMapsApiDirectionsUrl(): String {
        val waypoints = ("waypoints=optimize:true|"
                + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude
                + "|" + "|" + WALL_STREET.latitude + "," + WALL_STREET.longitude
                +"|" + "|" + BROOKLYN_BRIDGE.latitude + "," + BROOKLYN_BRIDGE.longitude)
        val OriDest =
            "origin=" + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude + "&destination=" + WALL_STREET.latitude + "," + WALL_STREET.longitude

        val sensor = "sensor=false"
        val params = "$OriDest&%20$waypoints&$sensor"
        val output = "json"
        return ("https://maps.googleapis.com/maps/api/directions/"
                + output + "?" + params)
    }

以上方法为我提供了包含我的来源和目的地以及Google处理信息并返回所需的JSON值所需的其他参数的URL。因此,在将其传递给Asyntask调用的那一刻,我将Google API KEY附加为:

val url = getMapsApiDirectionsUrl()+"&key=API_KEY"
        val downloadTask = ReadTask(this)
        downloadTask.execute(url)

就是这样!!! 因此请确保在将Google API_KEY附加到您的网址之前,再将其传递到Asyntask类中。 希望这对某人有帮助:真是欣喜若狂,我终于想通了:)