在Google地图上显示通过EditText输入的地址的路线

时间:2019-01-18 11:32:26

标签: android kotlin

对于使用编辑文本上的起始地址和目标地址输入的地址如何在Google地图上绘制路线感到困惑。 因此,我有一个由用户获取地址的原始Edittext和一个目标EditText,以及一个将地址转换为纬度和经度的按钮,这是通过在方法中将地址作为ArrayList传递来实现的。之后,我在Button中调用了MapAsync(this),但是我的代码没有响应。 我知道缺少某些东西,但我不知道。从昨天开始,我一直在研究此问题,但没有得到答复。

请我需要我所能获得的所有帮助。预先感谢。

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
  private lateinit var mMap: GoogleMap
  private var editOrigin : EditText ?= null
  private var editDestination: EditText ?= null
  var markerPoints: ArrayList<LatLng>?= null
  private var allLatLng: ArrayList<String>?= null
  private var LatLongitude: List<LatLngModel>?= null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps)
    markerPoints = ArrayList()
    allLatLng = ArrayList()

    editDestination = findViewById(R.id.editDestination)
    editOrigin = findViewById(R.id.editOrigin)
    // 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)

    findViewById<Button>(R.id.buttonSubmit).setOnClickListener {

        val origin = editOrigin!!.text.toString()
        val destination = editDestination!!.text.toString()


        allLatLng!!.add(origin)
        allLatLng!!.add(destination)
        LatLongitude = getCompleteAddressString(allLatLng!!)
        Log.d("TAGGY", LatLongitude.toString())
        mapFragment.getMapAsync(this)

    }

}

@SuppressLint("StaticFieldLeak")
inner class DownloadTask : AsyncTask<String,Int,String>() {

    override fun doInBackground(vararg url: String): String {

        var data = ""

        try {
            data = downloadUrl(url[0])
        } catch (e: Exception) {
            Log.d("Background Task", e.toString())
        }

        return data
    }

    override fun onPostExecute(result: String) {
        super.onPostExecute(result)

        val parserTask = ParserTask()
        parserTask.execute(result)
    }

}

inner class ParserTask : AsyncTask<String, Int, List<List<HashMap<String, String>>>>() {

    override fun doInBackground(vararg p0: String?): List<List<HashMap<String, String>>>? {

        val jObject: JSONObject
        var routes: List<List<HashMap<String, String>>>?

        try {
            jObject =  JSONObject(p0[0])
            val parser =  DirectionsJSONParser()

            routes = parser.parse(jObject)
            return routes!!

        } catch ( e: Exception) {
        }
        return null
    }

    // Parsing the data in non-ui thread

    override fun onPostExecute(result: List<List<HashMap<String, String>>>?) {
        super.onPostExecute(result)
        var points : ArrayList<LatLng>?= null

        var lineOptions:  PolylineOptions ? = null
        val markerOptions =  MarkerOptions()

        for (  i in 0 ..result!!.size ) {
            points =  ArrayList()
            lineOptions =  PolylineOptions()

            val path = result[i]

            for (j in 0 .. path.size) {
                val  point = path[j]
                val lat = java.lang.Double.parseDouble(point["lat"] as String?)
                val lng = java.lang.Double.parseDouble(point["lng"] as String?)

                val position = LatLng(lat, lng)

                points.add(position)
            }

            lineOptions.addAll(points)
            lineOptions.width(12f)
            lineOptions.color(Color.RED)
            lineOptions.geodesic(true)

        }

  // Drawing polyline in the Google Map for the i-th route
        mMap.addPolyline(lineOptions)
    }
}


@Throws(IOException::class)
private fun downloadUrl(strUrl: String): String {
    var data = ""
    var iStream: InputStream? = null
    var urlConnection: HttpURLConnection? = null
    try {
        val url = URL(strUrl)

        urlConnection = url.openConnection() as HttpURLConnection

        urlConnection.connect()

        iStream = urlConnection.inputStream

        val br = BufferedReader(InputStreamReader(iStream))

        val sb = StringBuffer()
        while (true) {
            val line = br.readLine()
            if (line != null) {
                sb.append(line)

            } else {
                Log.i("TAG", "HTTP RESPONSE" + sb.toString())
                return sb.toString()
            }
            data = sb.toString()

            br.close()
        }



    } catch (e: Exception) {
        Log.d("Exception", e.toString())
    } finally {
        iStream!!.close()
        urlConnection!!.disconnect()
    }
    return data
}
private fun getDirectionsUrl(origin: LatLng, dest: LatLng): String {

    // Origin of route
    val str_origin = "origin=" + origin.latitude + "," + origin.longitude

    // Destination of route
    val str_dest = "destination=" + dest.latitude + "," + dest.longitude

    // Sensor enabled
    val sensor = "sensor=false"
    val mode = "mode=driving"

    // Building the parameters to the web service
    val parameters = "$str_origin&$str_dest&$sensor&$mode"

    // Output format
    val output = "json"

    // Building the url to the web service


    return "https://maps.googleapis.com/maps/api/directions/$output?$parameters"
}
private fun getCompleteAddressString(addressList: ArrayList<String>): List<LatLngModel> {
    val strAdd = ArrayList<LatLngModel>()
    val latLngModel = LatLngModel()

    var lat: String? = null
    var lng: String? = null
    val geocoder = Geocoder(this, Locale.getDefault())
    try {
        for (a in addressList){
            val addresses = geocoder.getFromLocationName(a, 1)

            if (addresses != null && addresses.size > 0) {
                val address = addresses[0]
                val sb = StringBuilder()

                val lat = address.latitude
                val Lng = address.longitude


                    latLngModel.latitude = lat
                    latLngModel.longitude = Lng
                    strAdd.add(latLngModel)


                sb.append(address.latitude).append("\n")
                sb.append(address.longitude).append("\n")
            }else {
                Log.w("My Current addressList", "No Address returned!")
            }
        }

    } catch (e: Exception) {
        e.printStackTrace()
        Log.w("My Current addressList", "Cannot get Address!")
    }

    return strAdd
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap
    var lat1: Double
    var lng1: Double
    val options = MarkerOptions()
    var latlng: LatLng? = null
    // 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))
    try{
        if (markerPoints!!.size >1){
            markerPoints!!.clear()
            mMap.clear()
        }
        if (LatLongitude != null){
            for (v in LatLongitude!!){
                lat1 = v.latitude
                lng1 = v.longitude
                latlng  = LatLng(lat1,lng1)
            }


            markerPoints!!.add(latlng!!)


            options.position(latlng)
            if (markerPoints!!.size == 1){
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
            }
            else if (markerPoints!!.size == 2){
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
            }
            // Add new marker to the Google Map Android API V2
            mMap.addMarker(options)

        }
    }catch (e: Exception){
        Log.i("TAG", e.message)
    }
        // Checks, whether start and end locations are captured
        if (markerPoints!!.size >= 2) {
            val origin = markerPoints!![0]
            val dest = markerPoints!![1]

            // Getting URL to the Google Directions API
            val url = getDirectionsUrl(origin, dest)

            DownloadTask().execute(url)
        }


}


}

1 个答案:

答案 0 :(得分:-1)

PathGoogleMapActivity.java

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);
    }
}
}

Httpconnection.java

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;
}

}

PathJsonparser.java

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;
}
}