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("@#@$#@#$@#!#@$@$#@ 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());
    }
}
}
4

2 に答える 2

0

スレッドが終了したら、マップを設定する必要があります。あなたのコードは、start() メソッドの後に終了するまで待機しません。

スレッドの最後で Hanlder を使用するか、AsyncTask を使用することをお勧めします。私は後者を支持します。

マップにマーカーを追加する前にスレッドが終了しているため、おそらくデバッグ中に機能します。

于 2012-09-18T11:28:42.007 に答える
0

以下は、マップビューに道路を表示するために使用されるコードです。独自のコードを微調整する必要があるため、これは 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;
}
}
于 2012-09-25T09:03:56.473 に答える