2012-09-18 90 views
2

我已經獲取了數組列表中所有附近地點的搜索結果,但我無法在地圖上顯示它們。未顯示覆蓋項

當我調試我的應用程序,在SitesOverlay()構造函數中添加斷點時,位置填充,但不是如果我作爲android應用程序運行。下面

我的代碼給出:

public class Map1 extends MapActivity { 
private MapView map = null; 
private MyLocationOverlay me = null; 
double source_lat; 
double source_lng; 
double destination_lat = 12.899915; 
double destination_lng = 80.243969; 
Boolean isLocationFound = false; 
List<Place> arlPlaces = new ArrayList<Place>(); 

@SuppressWarnings("deprecation") 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    new Thread(new Runnable() { 

     public void run() { 
      System.out.println("@#@#@#@# main() @#@#@#@#"); 
      String strRequestUrl = ""; 
      try { 

       URL url = new URL(strRequestUrl); 
       URLConnection yc = url.openConnection(); 
       BufferedReader in = new BufferedReader(
         new InputStreamReader(yc.getInputStream())); 
       String inputLine; 
       Place place = null; 

       while ((inputLine = in.readLine()) != null) { 

        if (inputLine.contains("name")) { 
         place = new Place(); 
         place.setStrName(inputLine.substring(
           inputLine.indexOf(">") + 1, 
           inputLine.lastIndexOf("<"))); 
        } 
        if (inputLine.contains("vicinity")) { 
         place.setStrAddress(inputLine.substring(
           inputLine.indexOf(">") + 1, 
           inputLine.lastIndexOf("<"))); 
        } 
        if (inputLine.contains("lat")) { 
         place.setDblLatitude(Double.valueOf(inputLine 
           .substring(inputLine.indexOf(">") + 1, 
             inputLine.lastIndexOf("<")))); 
        } 
        if (inputLine.contains("lng")) { 
         place.setDblLongitude(Double.valueOf(inputLine 
           .substring(inputLine.indexOf(">") + 1, 
             inputLine.lastIndexOf("<")))); 
         arlPlaces.add(place); 
        } 
       } 
       in.close(); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }).start(); 

    map = (MapView) findViewById(R.id.map); 

    map.getController().setCenter(getPoint(12.899915, 80.243969)); 
    map.setStreetView(true); 
    map.setSatellite(false); 
    map.getController().setZoom(15); 
    map.setBuiltInZoomControls(true); 

    Drawable marker = getResources().getDrawable(R.drawable.marker); 

    marker.setBounds(0, 0, marker.getIntrinsicWidth(), 
      marker.getIntrinsicHeight()); 

    map.getOverlays().add(new SitesOverlay(marker)); 

    me = new MyLocationOverlay(this, map); 
    map.getOverlays().add(me); 
    Button b1 = (Button) findViewById(R.id.button1); 
    Button b2 = (Button) findViewById(R.id.button2); 
    Button btnNearby = (Button) findViewById(R.id.button3); 

    btnNearby.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 

     } 
    }); 

    b2.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 

      switch (v.getId()) { 
      case R.id.button2: 
       if (map.isSatellite() == false) { 

        map.setSatellite(true); 

       } 

       break; 

      } 
     } 
    }); 

    b1.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      switch (v.getId()) { 
      case R.id.button1: 
       if (map.isSatellite() == true) { 

        map.setSatellite(false); 

       } 
       break; 
      } 
     } 
    }); 
} 

@Override 
protected boolean isRouteDisplayed() { 
    return (false); 
} 

private GeoPoint getPoint(double lat, double lon) { 
    return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0))); 
} 

private class SitesOverlay extends ItemizedOverlay<OverlayItem> { 
    private List<OverlayItem> items = new ArrayList<OverlayItem>(); 

    public SitesOverlay(Drawable marker) { 
     super(marker); 

     boundCenterBottom(marker); 
     items.add(new OverlayItem(getPoint(12.899915, 80.243969), "", 
       "Mantri Signature Villas" + "\n" + "ECR Link Road, Chennai")); 

     Iterator<Place> iterator = arlPlaces.iterator(); 

     while (iterator.hasNext()) { 
      Place place = (Place) iterator.next(); 
      System.out.println("@#@$#@#[email protected]#!#@[email protected]$#@ iterator"); 
      items.add(new OverlayItem(getPoint(place.getDblLatitude(), 
        place.getDblLongitude()),place.getStrName(), place.getStrAddress())); 

     } 

     populate(); 
    } 

    @Override 
    protected OverlayItem createItem(int i) { 
     return (items.get(i)); 
    } 

    @Override 
    protected boolean onTap(final int i) { 
     // Toast.makeText(A.this, 
     // items.get(i).getSnippet(), 
     // Toast.LENGTH_SHORT).show(); 

     AlertDialog.Builder alert = new AlertDialog.Builder(Map1.this); 

     if (items 
       .get(i) 
       .getSnippet() 
       .equalsIgnoreCase(
         "Mantri Signature Villas\nECR Link Road, Chennai")) { 
      alert.setTitle(items.get(i).getSnippet()); 
      alert.setMessage("Would you like to find the Route?"); 
      // alert.setIcon(R.drawable.mnlo); 
      alert.setPositiveButton("Yes", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 

          LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
          Location myLocation1 = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          Location myLocation = locationManager 
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

          if (myLocation != null) { 
           String uri = "http://maps.google.com/maps?saddr=" 
             + (myLocation.getLatitude()) 
             + "," 
             + (myLocation.getLongitude()) 
             + "&daddr=" 
             + destination_lat 
             + "," 
             + destination_lng; 
           Intent intent = new Intent(
             android.content.Intent.ACTION_VIEW, 
             Uri.parse(uri)); 
           intent.setClassName(
             "com.google.android.apps.maps", 
             "com.google.android.maps.MapsActivity"); 
           startActivity(intent); 
          } else if (myLocation1 != null) { 
           String uri = "http://maps.google.com/maps?saddr=" 
             + (myLocation1.getLatitude()) 
             + "," 
             + (myLocation1.getLongitude()) 
             + "&daddr=" 
             + destination_lat 
             + "," 
             + destination_lng; 
           Intent intent = new Intent(
             android.content.Intent.ACTION_VIEW, 
             Uri.parse(uri)); 
           intent.setClassName(
             "com.google.android.apps.maps", 
             "com.google.android.maps.MapsActivity"); 
           startActivity(intent); 
          } else { 
           Intent intent = new Intent(
             getBaseContext(), Map1.class); 
           startActivity(intent); 

          } 

         } 
        }); 
      alert.setNegativeButton("No", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
         } 
        }); 

      alert.show(); 
     } else { 
      alert.setTitle(items.get(i).getSnippet()); 
      alert.setMessage("Would you like to find the Route?"); 
      alert.setPositiveButton("Yes", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 

          String uri = "http://maps.google.com/maps?saddr=" 
            + items.get(i).getPoint() 
            + "&daddr=" 
            + destination_lat 
            + "," 
            + destination_lng; 
          Intent intent = new Intent(
            android.content.Intent.ACTION_VIEW, Uri 
              .parse(uri)); 
          intent.setClassName(
            "com.google.android.apps.maps", 
            "com.google.android.maps.MapsActivity"); 
          startActivity(intent); 

         } 
        }); 
      alert.setNegativeButton("No", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
         } 
        }); 

      alert.show(); 
     } 

     return (true); 
    } 

    public int size() { 
     return (items.size()); 
    } 
} 
} 

回答

0

線程完成後,您應該填充地圖。你的代碼不會等待,直到start()方法結束。

我建議你或者嘗試在線程結束時使用Hanlder,或者使用AsyncTask工作。我贊成後者。

它可能在調試過程中起作用,因爲在將標記添加到地圖之前線程已完成。

+0

謝謝..它的工作..我想在地圖上顯示不同的標記..我怎麼能使用單個覆蓋? – vjamit

+0

https://developers.google.com/maps/documentation/android/hello-mapview 這是如何使用mapview以及如何添加多個標記的一個很好的示例。 – ePeace

+0

再次感謝..目前用於顯示兩個地方之間的駕駛方向我在設備上使用谷歌地圖..就像當我們點擊任何地方它啓動谷歌地圖應用程序並顯示方向..而不是我可以繪製路徑在相同的MapView上使用疊加?如果可能的話,可以分享一些示例代碼或鏈接..我確實嘗試過,但是我可以在地圖上繪製的是兩個選定點之間的直線.. – vjamit

0

下面是代碼是用來顯示在mapview道路上,這可能不適用於你100%,因爲你可能需要調整自己的代碼,但隨時提問。

在你的活動:

public class NavigationTask extends AsyncTask<Void, Void, Void> { 
    Road mRoad; 
    String startname = "", destname =""; 
    @Override 
    protected Void doInBackground(Void... params) { 
     String url = getUrl(Double.parseDouble(driveobj.get("startLocationLat")), Double.parseDouble(driveobj.get("startLocationLon")), Double.parseDouble(driveobj.get("endLocationLat")), Double.parseDouble(driveobj.get("endLocationLon"))); 
     String json = Internet.request(url, null); 
     mRoad = RoadProvider.getRoute(json); 



     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     //from.setText(startname); 
     //to.setText(destname); 

     MapOverlay mapOverlay = new MapOverlay(mRoad, mapview); 
     List<Overlay> listOfOverlays = mapview.getOverlays(); 
     listOfOverlays.add(mapOverlay); 
     mapview.invalidate(); 
     super.onPostExecute(result); 
    } 

} 

public String getUrl(double fromLat, double fromLon, double toLat, double toLon) { 
    StringBuffer urlString = new StringBuffer(); 
    urlString.append("http://maps.googleapis.com/maps/api/directions/json?origin="); 
    urlString.append(Double.toString(fromLat)); 
    urlString.append(","); 
    urlString.append(Double.toString(fromLon)); 
    urlString.append("&destination=");// to 
    urlString.append(Double.toString(toLat)); 
    urlString.append(","); 
    urlString.append(Double.toString(toLon)); 
    urlString.append("&sensor=true"); 
    return urlString.toString(); 
} 

MapOverlay類

class MapOverlay extends com.google.android.maps.Overlay { 
    Road mRoad; 
    ArrayList<GeoPoint> mPoints = new ArrayList<GeoPoint>();; 

    public MapOverlay(Road road, MapView mv) { 
     mRoad = road; 
     if (road.points.size() > 0) { 
      mPoints.addAll(road.points); 
      showMarkers(mPoints); 
      int moveToLat = (mPoints.get(0).getLatitudeE6() + (mPoints.get(mPoints.size() - 1).getLatitudeE6() - mPoints.get(0).getLatitudeE6())/2); 
      int moveToLong = (mPoints.get(0).getLongitudeE6() + (mPoints.get(mPoints.size() - 1).getLongitudeE6() - mPoints.get(0).getLongitudeE6())/2); 
      GeoPoint moveTo = new GeoPoint(moveToLat, moveToLong); 

      int minLatitude = Integer.MAX_VALUE; 
      int maxLatitude = Integer.MIN_VALUE; 
      int minLongitude = Integer.MAX_VALUE; 
      int maxLongitude = Integer.MIN_VALUE; 
      for (GeoPoint p : mPoints) { 
       int lati = p.getLatitudeE6(); 
       int lon = p.getLongitudeE6(); 

       maxLatitude = Math.max(lati, maxLatitude); 
       minLatitude = Math.min(lati, minLatitude); 
       maxLongitude = Math.max(lon, maxLongitude); 
       minLongitude = Math.min(lon, minLongitude); 
      } 

      MapController mapController = mv.getController(); 
      mapController.zoomToSpan(Math.abs(maxLatitude - minLatitude), Math.abs(maxLongitude - minLongitude)); 
     } 
    } 

    @Override 
    public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) { 
     super.draw(canvas, mv, shadow); 
     drawPath(mv, canvas); 
     return true; 
    } 

    public void drawPath(MapView mv, Canvas canvas) { 
     int x1 = -1, y1 = -1, x2 = -1, y2 = -1; 
     Paint paint = new Paint(); 
     paint.setColor(LO.titleBackgroundColor+0xDE000000); 
     paint.setStyle(Paint.Style.STROKE); 
     paint.setStrokeWidth(3); 
     for (int i = 0; i < mPoints.size(); i++) { 
      Point point = new Point(); 
      mv.getProjection().toPixels(mPoints.get(i), point); 
      x2 = point.x; 
      y2 = point.y; 
      if (i > 0) { 
       canvas.drawLine(x1, y1, x2, y2, paint); 
      } 
      x1 = x2; 
      y1 = y2; 
     } 
    } 
} 

MarkerOverLay類:

class MarkerOverlay extends ItemizedOverlay<OverlayItem> { 
    private ArrayList<OverlayItem> overlays = new ArrayList<OverlayItem>(); 

    public MarkerOverlay(Drawable defaultMarker) { 
     super(boundCenterBottom(defaultMarker)); 
    } 

    public void addOverlay(OverlayItem overlay) { 
     overlays.add(overlay); 
     populate(); 
    } 

    @Override 
    protected OverlayItem createItem(int i) { 
     return overlays.get(i); 
    } 

    @Override 
    public int size() { 
     return overlays.size(); 
    } 

} 

RoadProvider類:

public class RoadProvider { 

public static Road getRoute(String json) { 
    Road road = new Road(); 
    try { 
     JSONObject route = new JSONObject(json); 
     JSONArray routes = route.getJSONArray("routes"); 
     JSONArray legs = routes.getJSONObject(0).getJSONArray("legs"); 
     JSONArray steps = legs.getJSONObject(0).getJSONArray("steps"); 
     for(int i = 0, len = steps.length(); i < len; i++) { 
      JSONObject step = steps.getJSONObject(i); 
      if(i == 0) { 
       if(step.has("start_location")) { 
        JSONObject start = step.getJSONObject("start_location"); 
        double lon = Double.parseDouble(start.getString("lng")); 
        double lat = Double.parseDouble(start.getString("lat")); 
        GeoPoint point = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6)); 
        road.add(point); 
       } 
      } 
      if(step.has("end_location")) { 
       JSONObject start = step.getJSONObject("end_location"); 
       double lon = Double.parseDouble(start.getString("lng")); 
       double lat = Double.parseDouble(start.getString("lat")); 
       GeoPoint point = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6)); 
       road.add(point); 
      } 

     } 
    } catch (Exception e) { 
     e.fillInStackTrace(); 
     return null; 
    } 
    return road; 
} 
} 
+0

嗨,我需要知道如何將一個字節[]轉換爲JSON對象.. – vjamit