2014-09-29 32 views
0

在Google Map中,當我調試項目時,錯誤出現在這一行上:ArrayList directionPoint = md.getDirection(doc);並顯示Source未在Library類中找到ActivityThread.PerformLunchActivity()方法。 // MainActivity代碼下面:在谷歌地圖項目源未找到異常顯示在android中

public class FirstMap extends Activity { 
GMapDirection md; 
private GoogleMap mMap; 
LatLng fromPosition = new LatLng(13.687140112679154, 100.53525868803263); 
LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932); 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_firstmap); 
    mMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap(); 
     LatLng coordinates = new LatLng(13.685400079263206, 100.537133384495975);  
     mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 18)); 
     mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start")); 
     mMap.addMarker(new MarkerOptions().position(toPosition).title("End")); 
     md = new GMapDirection(); 
     Document doc = md.getDocument(fromPosition, toPosition, GMapDirection.MODE_DRIVING);  
     ArrayList<LatLng> directionPoint = md.getDirection(doc); 
     PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED); 
     for(int i = 0 ; i < directionPoint.size() ; i++) {   
      rectLine.add(directionPoint.get(i)); 
     } 
     mMap.addPolyline(rectLine);  
} 

}

// GMapDirection和getDirection()方法的代碼:

public class GMapDirection { 
    public final static String MODE_DRIVING = "driving"; 
    public final static String MODE_WALKING = "walking"; 

    public GMapDirection() { } 

    public Document getDocument(LatLng start, LatLng end, String mode){ 
     //see link for xml : https://developers.google.com/maps/documentation/geocoding/ 
     String url = "http://maps.googleapis.com/maps/api/directions/xml?" 
       + "origin=" + start.latitude + "," + start.longitude 
       + "&destination=" + end.latitude + "," + end.longitude 
       + "&sensor=false&units=metric&mode=driving"; 
     Log.d("GoogleMapsDirection", url); 
     try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpContext localContext = new BasicHttpContext(); 
      HttpPost httpPost = new HttpPost(url); 
      HttpResponse response = httpClient.execute(httpPost, localContext); 
      InputStream in = response.getEntity().getContent(); 
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
      Document doc = builder.parse(in); 
      return doc; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    public ArrayList<LatLng> getDirection(Document doc) { 
     // TODO Auto-generated method stub 
     NodeList nl1, nl2, nl3; 
     ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>(); 
     nl1 = doc.getElementsByTagName("step"); 
     if (nl1.getLength() > 0) { 
      for (int i = 0; i < nl1.getLength(); i++) { 
       Node node1 = nl1.item(i); 
       nl2 = node1.getChildNodes(); 

       Node locationNode = nl2.item(getNodeIndex(nl2, "start_location")); 
       nl3 = locationNode.getChildNodes(); 
       Node latNode = nl3.item(getNodeIndex(nl3, "lat")); 
       double lat = Double.parseDouble(latNode.getTextContent()); 
       Node lngNode = nl3.item(getNodeIndex(nl3, "lng")); 
       double lng = Double.parseDouble(lngNode.getTextContent()); 
       listGeopoints.add(new LatLng(lat, lng)); 

       locationNode = nl2.item(getNodeIndex(nl2, "polyline")); 
       nl3 = locationNode.getChildNodes(); 
       latNode = nl3.item(getNodeIndex(nl3, "points")); 
       ArrayList<LatLng> arr = decodePoly(latNode.getTextContent()); 
       for(int j = 0 ; j < arr.size() ; j++) { 
        listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude)); 
       } 

       locationNode = nl2.item(getNodeIndex(nl2, "end_location")); 
       nl3 = locationNode.getChildNodes(); 
       latNode = nl3.item(getNodeIndex(nl3, "lat")); 
       lat = Double.parseDouble(latNode.getTextContent()); 
       lngNode = nl3.item(getNodeIndex(nl3, "lng")); 
       lng = Double.parseDouble(lngNode.getTextContent()); 
       listGeopoints.add(new LatLng(lat, lng)); 
      } 
     } 

     return listGeopoints; 
    } 

     private int getNodeIndex(NodeList nl, String nodename) { 
      for(int i = 0 ; i < nl.getLength() ; i++) { 
       if(nl.item(i).getNodeName().equals(nodename)) 
        return i; 
      } 
       return -1; 
      } 


     private ArrayList<LatLng> decodePoly(String encoded) { 
      ArrayList<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 position = new LatLng((double) lat/1E5, (double) lng/1E5); 
       poly.add(position); 
      } 
      return poly; 
     } 
} 
+0

發佈您的logcat.so,可以找到確切的錯誤 – 2014-09-29 10:21:01

回答

0

與我的例子做:

活動代碼:

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
     View v   = inflater.inflate(R.layout.fragment_location, container, false); 
     googleMap  = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); 

     setOptionsItem(R.drawable.ic_mobileedge_navto, new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       findDirections(((ScreenLocation)getScreen()).getMap().getCenterLat(), ((ScreenLocation)getScreen()).getMap().getCenterLon(), GMapV2Direction.MODE_DRIVING); 
      } 
     }); 

     MapsInitializer.initialize(getActivity().getApplicationContext()); 

     googleMap.addMarker(new MarkerOptions() 
       .position(new LatLng(((ScreenLocation)getScreen()).getMap().getCenterLat(), ((ScreenLocation)getScreen()).getMap().getCenterLon())) 
       .title(getString(R.string.event_location)) 
       .icon(BitmapDescriptorFactory 
         .fromResource(R.drawable.ic_mobileedge_navpoint))); 

     // Move the camera instantly to hamburg with a zoom of 15. 
     googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(((ScreenLocation)getScreen()).getMap().getCenterLat(), ((ScreenLocation)getScreen()).getMap().getCenterLon()), 15)); 

     // Zoom in, animating the camera. 
     googleMap.animateCamera(CameraUpdateFactory.zoomTo(12), 1000, null); 

     return v; 
    } 


    public void findDirections(double toPositionDoubleLat, double toPositionDoubleLong, String mode) 
    { 
     new GetDirectionsAsyncTask(MapFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, String.valueOf(toPositionDoubleLat), String.valueOf(toPositionDoubleLong), mode); 
    } 


// Function to Draw Lines in GMap 
public void handleGetDirectionsResult(ArrayList directionPoints) 
    { 
     PolylineOptions rectLine = new PolylineOptions().width(10).color(getResources().getColor(R.color.location_line)); 

     for(Object l : directionPoints) 
     { 
      rectLine.add((LatLng)l); 
     } 

     googleMap.addPolyline(rectLine); 
    } 

的AsyncTask:

public class GetDirectionsAsyncTask extends AsyncTask<String, Object, ArrayList> 
{ 

    private MapFragment  activity; 
    private Exception  exception; 

    public GetDirectionsAsyncTask(MapFragment activity) 
    { 
     super(); 
     this.activity = activity; 
    } 

    @Override 
    protected void onPreExecute() 
    { 
     super.onPreExecute(); 
    } 

    @Override 
    public void onPostExecute(ArrayList result) 
    { 

     if (exception == null) 
     { 
      activity.handleGetDirectionsResult(result); 
     } 
     else 
     { 
      processException(); 
     } 
    } 

    @Override 
    protected ArrayList doInBackground(String... params) 
    { 
     String toLat = params[0]; 
     String toLon = params[1]; 
     String mode  = params[2]; 

     try 
     { 
      LocationManager lm = (LocationManager) activity.getActivity().getSystemService(Context.LOCATION_SERVICE); 
      List<String> providers = lm.getProviders(true); 

      /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/ 
      Location location = null; 

      for (int i=providers.size()-1; i>=0; i--) { 
       location = lm.getLastKnownLocation(providers.get(i)); 
       if (location != null) break; 
      } 

      double latitude; 
      double longitude; 
      latitude     = location.getLatitude(); 
      longitude     = location.getLongitude(); 

      LatLng fromPosition   = new LatLng(latitude , longitude); 
      LatLng toPosition   = new LatLng(Double.valueOf(toLat), Double.valueOf(toLon)); 
      GMapV2Direction md   = new GMapV2Direction(); 
      Document doc    = md.getDocument(fromPosition, toPosition, mode); 

      return md.getDirection(doc); 
     } 
     catch (Exception e) 
     { 
      Debug.e(e.toString()); 
      exception = e; 
      return null; 
     } 
    } 

    private void processException() 
    { 
     Debug.d("Error Getting Location"); 
    } 
} 
0

嘗試使用此 - 在呼籲ParserTask Asyntask通過你的網址的AsyncTask -

url1 = "https://maps.googleapis.com/maps/api/directions/"....; 
    ParserTask parserTask = new ParserTask(); 
    // Invokes the thread for parsing the JSON data 
    parserTask.execute(url1); 

ParserTask類 -

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]); 
       DirectionsJSONParser parser = new DirectionsJSONParser(); 

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

        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(5); 
       lineOptions.color(Color.BLUE); 

      } 

      map.addPolyline(lineOptions); 
      for(int i=0;i<Dec.html_instructions.size();i++){ 
       sb.append((i+1)+". "+ Dec.html_instructions.get(i)+"<br>"); 
       //System.out.println("sb--"+sb); 
      } 
     }  

DirectionsJSONParser -

public class DirectionsJSONParser { 

    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */ 
    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++){ 
        Dec.distance=((JSONObject) ((JSONObject)jLegs.get(j)).get("distance")).get("text").toString(); 
        Dec.duration=((JSONObject) ((JSONObject)jLegs.get(j)).get("duration")).get("text").toString(); 
        Log.d("Distance",Dec.distance.toString()); 
        jSteps = ((JSONObject)jLegs.get(j)).getJSONArray("steps"); 

        /** Traversing all steps */ 
        for(int k=0;k<jSteps.length();k++){ 
         String polyline = ""; 
         if((boolean)(((JSONObject)jSteps.get(k)).has("html_instructions"))) 
         { 
          String html=(String)(((JSONObject)jSteps.get(k)).get("html_instructions")); 
          html=html.replaceAll("\\<.*?>",""); 
          Dec.html_instructions.add(html); 
         } 
         else 
         { 
          Dec.html_instructions.add("no html"); 
         } 
         if((boolean)(((JSONObject)jSteps.get(k)).has("maneuver"))) 
         { 
          String side=(String)(((JSONObject)jSteps.get(k)).get("maneuver")); 
          Dec.maneuver.add(side); 
         } 
         else 
         { 
          Dec.maneuver.add("No side"); 
         } 

         Dec.dis.add((String)((JSONObject)((JSONObject)jSteps.get(k)).get("distance")).get("text")); 
         Dec.dur.add((String)((JSONObject)((JSONObject)jSteps.get(k)).get("duration")).get("text")); 
         Dec.starting_lat.add((Double)((JSONObject)((JSONObject)jSteps.get(k)).get("start_location")).get("lat")); 
         Dec.starting_long.add((Double)((JSONObject)((JSONObject)jSteps.get(k)).get("start_location")).get("lng")); 
         Dec.ending_lat.add((Double)((JSONObject)((JSONObject)jSteps.get(k)).get("end_location")).get("lat")); 
         Dec.ending_long.add((Double)((JSONObject)((JSONObject)jSteps.get(k)).get("end_location")).get("lng")); 

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


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