
public voID ontouchMap(){ // Setting onclick event Listener for the map this.mapG3.setonMapClickListener(new OnMapClickListener() { @OverrIDe public voID onMapClick(LatLng point) { // Already two locations if (Geo4.this.markerPoints.size() > 1) { Geo4.this.markerPoints.clear(); Geo4.this.mapG3.clear(); } // Adding new item to the ArrayList Geo4.this.markerPoints.add(point); // Creating MarkerOptions MarkerOptions options = new MarkerOptions(); // Setting the position of the marker options.position(point); /** * For the start location,the color of marker is GREEN and for * the end location,the color of marker is RED. */ if (Geo4.this.markerPoints.size() == 1) { options.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); } else if (Geo4.this.markerPoints.size() == 2) { options.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_RED)); } // Add new marker to the Google Map AndroID API V2 Geo4.this.mapG3.addMarker(options); // Checks,whether start and end locations are captured if (Geo4.this.markerPoints.size() >= 2) { LatLng origin = Geo4.this.markerPoints.get(0); LatLng dest = Geo4.this.markerPoints.get(1); // Getting URL to the Google Directions API String url = Geo4.this.getDirectionsUrl(origin,dest); DownloadTask downloadTask = new DownloadTask(); // Start downloading Json data from Google Directions API downloadTask.execute(url); } } });}//-- END Method 这是我想要修改的方法,以便它查找我的updatedLatLng& wcbcLatLng而不是LatLng原点&该方法当前正在使用的LatLng dest.任何帮助,将不胜感激!这是我的完整活动:
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 java.util.ArrayList;import java.util.HashMap;import java.util.List;import org.Json.JsONObject;import androID.app.AlertDialog;import androID.content.Intent;import androID.graphics.color;import androID.location.LocationManager;import androID.os.AsyncTask;import androID.os.Bundle;import androID.support.v4.app.FragmentActivity;import androID.util.Log;import androID.vIEw.Menu;import androID.vIEw.MenuItem;import androID.vIEw.VIEw;import androID.Widget.button;import androID.Widget.TextVIEw;import androID.Widget.Toast;import com.Google.androID.gms.common.GooglePlayServicesUtil;import com.Google.androID.gms.maps.CameraUpdate;import com.Google.androID.gms.maps.CameraUpdateFactory;import com.Google.androID.gms.maps.GoogleMap;import com.Google.androID.gms.maps.GoogleMap.OnMapClickListener;import com.Google.androID.gms.maps.SupportMapFragment;import com.Google.androID.gms.maps.model.BitmapDescriptorFactory;import com.Google.androID.gms.maps.model.LatLng;import com.Google.androID.gms.maps.model.LatLngBounds;import com.Google.androID.gms.maps.model.Marker;import com.Google.androID.gms.maps.model.MarkerOptions;import com.Google.androID.gms.maps.model.polylineoptions;import androID.location.Criteria;import androID.location.Location;import androID.location.LocationListener;import androID.location.LocationManager;import androID.provIDer.Settings;public class Geo4 extends FragmentActivity implements LocationListener {GoogleMap mapG3;ArrayList<LatLng> markerPoints;TextVIEw mAPInfo_TV;LocationManager locMan;SupportMapFragment sMf;button back_btn,zoom_btn;MarkerOptions startMO,wcbcMO,broncoMO;MarkerOptions markers;Marker currentMarker,wcbcmarker,broncoMarker;LatLng updatedLatLng,directionsLatLng;LatLng wcbcLatLng = new LatLng(30.393903,-97.682871);LatLng oskiLatLng = new LatLng(30.474570,-97.973889);LatLng point,point3t,point4t;CameraUpdate cameraUpdate;@OverrIDeprotected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.geo3); back_btn = (button) findVIEwByID(R.ID.backMap_g3_btn); zoom_btn = (button) findVIEwByID(R.ID.marker_g3_btn); this.mAPInfo_TV = (TextVIEw) this.findVIEwByID(R.ID.map_g3Info_TV); // Initializing this.markerPoints = new ArrayList<LatLng>(); // Getting reference to SupportMapFragment of the activity_main sMf = (SupportMapFragment) this.getSupportFragmentManager() .findFragmentByID(R.ID.map_g3_FRAG); // Getting Map for the SupportMapFragment this.mapG3 = sMf.getMap(); // --- fire Methods GooglePlay(); getCurrentLocation(); ontouchMap(); // --- END fire Methods // --- Back button back_btn.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw arg0) { // mapG3.clear(); Intent backmAPI = new Intent( "com.my.package.button_INTERFACE"); startActivity(backmAPI); } }); // --- end Back button // --- Zoom button zoom_btn.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw arg0) { getDirections4T(point4t); } }); // --- end Zoom button}// --- END onCreate// --- Methods ----public voID GooglePlay() { // ---- Google Play // Getting Google Play availability status int status = GooglePlayServicesUtil .isGooglePlayServicesAvailable(getBaseContext()); if (status != ConnectionResult.SUCCESS) { // Google Play Services are // not available int requestCode = 10; Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,this,requestCode); dialog.show(); } else { // Google Play Services are available //Toast.makeText(getApplicationContext(),"Services Launched Fo Sho'",Toast.LENGTH_SHORT).show(); }}// ---- END Methodpublic voID getCurrentLocation(){ // Getting LocationManager object from System Service LOCATION_SERVICE locMan = (LocationManager) getSystemService(LOCATION_SERVICE); boolean enabledGPS = locMan .isProvIDerEnabled(LocationManager.GPS_PROVIDER); boolean enableDWiFi = locMan .isProvIDerEnabled(LocationManager.NETWORK_PROVIDER); // Check if enabled and if not send user to the GPS settings if (!enabledGPS && !enableDWiFi) { Toast.makeText(getApplicationContext(),"GPS signal not found",Toast.LENGTH_LONG).show(); Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } // Creating a criteria object to retrIEve provIDer Criteria criteria = new Criteria(); // Getting the name of the best provIDer String provIDer = locMan.getBestProvIDer(criteria,true); // Getting Current Location From GPS Location olc = locMan.getLastKNownLocation(provIDer); if (olc != null) { onLocationChanged(olc); } locMan.requestLocationUpdates(provIDer,20000,this);}//--- END Methodpublic voID zoomToFit() { // --- zoom to fit LatLngBounds.Builder builder = new LatLngBounds.Builder(); builder.include(wcbcLatLng); builder.include(updatedLatLng); LatLngBounds bounds = builder.build(); int padding = 50; // offset from edges of the map in pixels cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds,padding); mapG3.animateCamera(cameraUpdate); // --- END zoom to fit}// --- END Methodpublic voID adDWcbcmarkerOption() { wcbcMO = new MarkerOptions().position(wcbcLatLng).Title( "Destination"); wcbcMO.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_VIolET)); mapG3.addMarker(wcbcMO); cameraUpdate = CameraUpdateFactory.newLatLngZoom(wcbcLatLng,15); mapG3.animateCamera(cameraUpdate);}// --- END Methodpublic voID getDirections4T(LatLng point4t) { Geo4.this.markerPoints.add(point4t); markers = new MarkerOptions(); markers.position(wcbcLatLng); markers.position(oskiLatLng); if (Geo4.this.markerPoints.size() == 1) { markers.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); } else if (Geo4.this.markerPoints.size() == 2) { markers.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_RED)); } Geo4.this.mapG3.addMarker(markers);}//--- END Methodpublic voID ontouchMap(){ // Setting onclick event Listener for the map this.mapG3.setonMapClickListener(new OnMapClickListener() { @OverrIDe public voID onMapClick(LatLng point) { // Already two locations if (Geo4.this.markerPoints.size() > 1) { Geo4.this.markerPoints.clear(); Geo4.this.mapG3.clear(); } // Adding new item to the ArrayList Geo4.this.markerPoints.add(point); // Creating MarkerOptions MarkerOptions options = new MarkerOptions(); // Setting the position of the marker options.position(point); /** * For the start location,dest); DownloadTask downloadTask = new DownloadTask(); // Start downloading Json data from Google Directions API downloadTask.execute(url); } } });}//-- END Methodprivate String getDirectionsUrl(LatLng updatedLatLng,LatLng dest) { // Origin of route String str_updatedLatLng = "origin=" + updatedLatLng.latitude + "," + updatedLatLng.longitude; // Destination of route String str_dest = "destination=" + dest.latitude + "," + dest.longitude; // Sensor enabled String sensor = "sensor=false"; // Building the parameters to the web service String parameters = str_updatedLatLng + "&" + str_dest + "&" + sensor; // Output format String output = "Json"; // Building the url to the web service String url = "https://maps.GoogleAPIs.com/maps/API/directions/" + output + "?" + parameters; return url;}/** A method to download Json data from url */private String downloadUrl(String strUrl) throws IOException { String data = ""; inputStream iStream = null; httpURLConnection urlConnection = null; try { URL url = new URL(strUrl); // Creating an http connection to communicate with url urlConnection = (httpURLConnection) url.openConnection(); // Connecting to url urlConnection.connect(); // Reading data from url 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 downloading url",e.toString()); } finally { iStream.close(); urlConnection.disconnect(); } return data;}// Fetches data from url passedprivate class DownloadTask extends AsyncTask<String,VoID,String> { // Downloading data in non-ui thread @OverrIDe protected String doInBackground(String... url) { // For storing data from web service String data = ""; try { // Fetching the data from web service data = Geo4.this.downloadUrl(url[0]); } catch (Exception e) { Log.d("Background Task",e.toString()); } return data; } // Executes in UI thread,after the execution of // doInBackground() @OverrIDe protected voID onPostExecute(String result) { super.onPostExecute(result); ParserTask parserTask = new ParserTask(); // Invokes the thread for parsing the JsON data parserTask.execute(result); }}/** A class to parse the Google Places in JsON format */private class ParserTask extends AsyncTask<String,Integer,List<List<HashMap<String,String>>>> { // Parsing the data in non-ui thread @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]); Geo3JsON parser = new Geo3JsON(); // Starts parsing data routes = parser.parse(jObject); } catch (Exception e) { e.printstacktrace(); } return routes; } // Executes in UI thread,after the parsing process @OverrIDe protected voID onPostExecute(List<List<HashMap<String,String>>> result) { ArrayList<LatLng> points = null; polylineoptions lineOptions = null; MarkerOptions markerOptions = new MarkerOptions(); String distance = ""; String duration = ""; if (result.size() < 1) { Toast.makeText(Geo4.this.getBaseContext(),"No Points",Toast.LENGTH_SHORT).show(); return; } // Traversing through all the routes for (int i = 0; i < result.size(); i++) { points = new ArrayList<LatLng>(); lineOptions = new polylineoptions(); // Fetching i-th route List<HashMap<String,String>> path = result.get(i); // Fetching all the points in i-th route for (int j = 0; j < path.size(); j++) { HashMap<String,String> point = path.get(j); if (j == 0) { // Get distance from the List distance = point.get("distance"); continue; } else if (j == 1) { // Get duration from the List duration = point.get("duration"); continue; } double lat = Double.parseDouble(point.get("lat")); double lng = Double.parseDouble(point.get("lng")); LatLng position = new LatLng(lat,lng); points.add(position); } // Adding all the points in the route to lineOptions lineOptions.addAll(points); lineOptions.wIDth(4); lineOptions.color(color.RED); } Geo4.this.mAPInfo_TV.setText("distance: " + distance + "les"); // Drawing polyline in the Google Map for the route Geo4.this.mapG3.addpolyline(lineOptions); }}// --- END Methods// --- onLocationListener@OverrIDepublic voID onLocationChanged(Location olc) { updatedLatLng = new LatLng(olc.getLatitude(),olc.getLongitude()); startMO = new MarkerOptions().position(updatedLatLng) .Title("You Are Here") .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)); mapG3.addMarker(startMO); adDWcbcmarkerOption(); locMan.removeUpdates(this);}@OverrIDepublic voID onProvIDerDisabled(String provIDer) { //}@OverrIDepublic voID onProvIDerEnabled(String provIDer) { //}@OverrIDepublic voID onStatusChanged(String provIDer,int status,Bundle extras) { //}// --- END onLocationListener@OverrIDeprotected voID onPause() { super.onPause(); overrIDePendingTransition(R.anim.fadein,R.anim.fadeout); finish();}// --- inflated menu@OverrIDepublic boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.wcbcv,menu); return true;}@OverrIDepublic boolean onoptionsItemSelected(MenuItem item) { switch (item.getItemID()) { case R.ID.menu_legalnotices: String licenseInfo = GooglePlayServicesUtil .getopenSourceSoftwarelicenseInfo(getApplicationContext()); AlertDialog.Builder licenseDialog = new AlertDialog.Builder( Geo4.this); licenseDialog.setTitle("Legal Notices"); licenseDialog.setMessage(licenseInfo); licenseDialog.show(); return true; } return super.onoptionsItemSelected(item);}// --- END inflated menu}解决方法 我想到了.我的ontouchMap()大部分都是获取ontouch信息并将这些整数转换为LatLng值.由于我已经拥有LatLng值,因此我只需要方法的最后三行来获取LatLng并从中获取JsON数据.所以我重写了首先添加MarkerOptions和LatLng值的方法,然后我添加了旧方法的最后3行.所以这就是我的新方法的样子,它可以正常工作(通过调用其他3种方法)并绘制折线并在TextVIEw中以英里显示距离. public voID addMarkers(){ wcbcMO = new MarkerOptions().position(wcbcLatLng) .Title("Destination") .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_VIolET)); mapG3.addMarker(wcbcMO); startMO = new MarkerOptions().position(updatedLatLng) .Title("You Are Here") .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)); mapG3.addMarker(startMO); // Getting URL to the Google Directions API String url = Geo4.this.getDirectionsUrl(updatedLatLng,wcbcLatLng); DownloadTask downloadTask = new DownloadTask(); // Start downloading Json data from Google Directions API downloadTask.execute(url);}//--- END Method 总结 以上是内存溢出为你收集整理的在Android上的Google Maps API v2中显示路线全部内容,希望文章能够帮你解决在Android上的Google Maps API v2中显示路线所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)