我有一张地图,我想在两点之间显示路线,问题是它总是显示我错误的路线。检查下面的图片,您将理解:
http://image.noelshack.com/fichiers/2014/21/1400859345-28297.jpg
这是我的代码: 用于获取路线的类: CalculItineraire.java:
package app.usthb;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.widget.Toast;
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.model.BitmapDescriptorFactory;
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 CalculItineraire extends AsyncTask<Void, Integer, Boolean>{
private ProgressDialog prog;
private GoogleMap map;
private Context context;
private ArrayList<LatLng> list;
private LatLng Source;
private LatLng Destination;
//======================= Constructeur:
public CalculItineraire(GoogleMap map, Context context, LatLng Source, LatLng Destination){
this.map = map;
this.context = context;
this.Source= Source;
this.Destination = Destination;
list = new ArrayList<LatLng>();
}
@Override
protected void onPreExecute(){
//Toast.makeText(context, "Calcule de l'initéraire en cours...", Toast.LENGTH_LONG).show();
prog = new ProgressDialog(context);
prog.setMessage("Calcule de l'initéraire en cours...");
prog.show();
}
@Override
protected Boolean doInBackground(Void... params) {
//Generation de l'url pour effectuer la requete:
String url = "http://maps.googleapis.com/maps/api/directions/xml?";
url += "origin="+Source.latitude+","+Source.longitude;
url += "&destination="+Destination.latitude+","+Source.longitude;
url += "&sensor=false&units=metric&mode=walking";
//Toast.makeText(context, url, Toast.LENGTH_LONG).show();
try {
//Lancer la requète:
InputStream in= new URL(url).openStream();
//======== Recuperation de la requète:
//Préparer le document a recevoir le resultat de la requète:
DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
docBF.setIgnoringComments(true);
DocumentBuilder docB = docBF.newDocumentBuilder();
final Document doc = docB.parse(in);
doc.getDocumentElement().normalize();
//Recuperer + tester le statut de la requète:
String statut = doc.getElementsByTagName("status").item(0).getTextContent();
if(!("OK".equals(statut))){
//Si ce n'est pas OK, on sort de la methode avec false
return false;
}
//=========== Recupéré les steps:
final Element elementLeg = (Element) doc.getElementsByTagName("leg").item(0);
NodeList ListStep = elementLeg.getElementsByTagName("step");
for(int i=0; i<ListStep.getLength(); i++){
Node Step = ListStep.item(i);
//Cast de Step vers Element, pour pourvoir acceder au elements fils de Step
Element ElementStep = (Element)Step;
//Decoder le <Poin></Point>...
this.decodePolylines(ElementStep.getElementsByTagName("points").item(0).getTextContent());
}
return true;
} catch (Exception e) {
return false;
}
}
//Exception:
private void processException()
{
Toast.makeText(context, "Exception!! ", Toast.LENGTH_LONG).show();
}
//onPostExecute!
protected void onPostExecute(Boolean result){
//Onlever le Progress!
prog.dismiss();
if(!result){
Toast.makeText(context, "result faux", 7000).show();
}else{
//Mise a jour de la carte:
//1. Ajouter un marker ROUGE pour le Depart:
MarkerOptions MarkerDp = new MarkerOptions();
MarkerDp.position(Source);
MarkerDp.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//2. le Polyline:
PolylineOptions polyline = new PolylineOptions();
polyline.color(Color.CYAN);
for(LatLng ltlg : list){
//Toast.makeText(context, "and we have: "+ltlg.toString(), Toast.LENGTH_LONG).show();
polyline.add(ltlg);
}
//3. Ajouter un marker BLEU pour la destination:
MarkerOptions MarkerDs = new MarkerOptions();
MarkerDs.position(Destination);
MarkerDs.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
//4. Mise a jour de la carte + camera :
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(Source, 14);
map.moveCamera(update);
map.addMarker(MarkerDp);
map.addPolyline(polyline);
map.addMarker(MarkerDs);
}
}
/**
* Méthode qui décode les points en latitude et longitudes
* Créer par http://jeffreysambells.com/
* full link: http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* @param points
*/
private void decodePolylines(final String encodedPoints) {
int index = 0;
int lat = 0, lng = 0;
while (index < encodedPoints.length()) {
int b, shift = 0, result = 0;
do {
b = encodedPoints.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 = encodedPoints.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
list.add(new LatLng((double)lat/1E5, (double)lng/1E5));
}
}
}
从主班获得rtoue:
new CalculItineraire(map, this, new LatLng(36.7146905, 3.17872614), new LatLng(36.71377454, 3.17724288)).execute();