2

I have got all the search results for nearby places in an array list, but I am unable to display them on the map.

When I debug my application, adding breakpoint inside the SitesOverlay() constructor, the places are populated, but not if I run as android application.

My code is given below:

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());
    }
}
}
MattH
  • 37,273
  • 11
  • 82
  • 84
vjamit
  • 195
  • 1
  • 2
  • 10

2 Answers2

0

You should populate the map after the thread is finished. Your code doesn't wait untill it's finished after the start() method.

I suggest your either try working with a Hanlder at the end of your thread, or that you work with a AsyncTask. I favor the latter.

It probably works during debug because your thread is finished before you add the markers to the map.

ePeace
  • 1,987
  • 1
  • 17
  • 23
  • thanks.. it worked.. i want to display different markers on the map.. how can i do that using single overlay ? – vjamit Sep 21 '12 at 06:22
  • https://developers.google.com/maps/documentation/android/hello-mapview This is a good example of how to use mapview and how to add multiple markers. – ePeace Sep 21 '12 at 07:54
  • thanks again.. currently for showing driving directions between two places i'm using google maps on the device.. like when we tap on any place it launches google maps app and shows the direction.. instead of that can i draw the path on the same MapView using overlays?? if it is possible plz share some sample code or links.. i did try that but all i can draw on the map is a straight line between two selected points.. – vjamit Sep 22 '12 at 10:47
  • That's a more complicated one. I know there is a google maps API that give directions between 2 locations in the form of point to point navigation. You can override the ondraw method of the overlay to draw all the lines you need to give directions. I'll have to look for sample code myself.. – ePeace Sep 24 '12 at 06:45
  • thanks.. i tried that and did succeed.. i'm able to draw the route correctly, but the lines are still straight between two points.. that is it is not following the road.. – vjamit Sep 25 '12 at 07:27
0

Below is the code is use to show roads on a mapview, this might not work 100% for you as you might have to tweak to your own code, but feel free to ask questions.

In your activity:

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

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:

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 class:

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;
}
}
ePeace
  • 1,987
  • 1
  • 17
  • 23