views:

1088

answers:

2

Hi Guys, after implementing some Android Apps, including several Map activities, I try to refresh the activity when the GPS listener's onLocationChanged() mehtod is called.

I have no idea how to tell the map activity to refresh on its own and display the new coords...

the coords to store will have to be in global values, so that the location listener will have access to it.

In my sample GPS-class (see code below) I just changed the text of a text view....but how to do that in map view?

private class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {
        final TextView tv = (TextView) findViewById(R.id.myTextView);
        if (loc != null) {
            tv.setText("Location changed : Lat: " + loc.getLatitude()
                            + " Lng: " + loc.getLongitude());
        }
    }

I think the solution of this Problem won't be very difficult, but I just need the beginning ;-)

This whole app shall work like a really simple navigation system.

It would be great if someone could help me a little bit further :)

nice greetings, Poeschlorn

+2  A: 

You can call View::invalidate() ( http://developer.android.com/reference/android/view/View.html#invalidate() ), so the View will redraw using View::onDraw() method. To use it, you should move your code to a View (MapView for example), to its onDraw() method.

WarGoth
in a strange way my code (see below) doesn't overwrite the "old" geoPoints....strange, strange...
poeschlorn
do I have to add the new MapView class to the list of overlays?
poeschlorn
A: 

thanks for the answer, in theory that sounds great. But I retrieve no Update on my map... the comment function offers to small space for my code, that's why I post it right here:

public class NavigationActivity extends MapActivity {

//  static GeoPoint posCar;
//  static GeoPoint posUser;
MapController mc;
LinearLayout linearLayout;
MapView mapView;
Intent intent = null;

static GeoPoint posCar = PositionController.getCoordsCar();
static GeoPoint posUser = PositionController.getCoordsUser();

private LocationManager lm;
private LocationListener locationListener = new MyLocationListener();

int routeDefaultColor = Color.RED;

/**
 * Called when the activity is first created
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main); // Use Layout "main.xml"

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0,
            locationListener);

    mapView = (MapView) findViewById(R.id.mapView); // Gets the map view by
    // ID
    mapView.setBuiltInZoomControls(true); // Enables the zoom buttons
    mc = mapView.getController();

    // Receive intent
    intent = getIntent();

    //posCar = PositionController.getCoordsCar();
    //posUser = PositionController.getCoordsUser();
    // Show only "car position" or "full route"

    // Show the full route
    // Calculates the geographic middle between start and end point
    int latMiddle = (int) ((posCar.getLatitudeE6() + posUser
            .getLatitudeE6()) / 2);
    int lonMiddle = (int) ((posCar.getLongitudeE6() + posUser
            .getLongitudeE6()) / 2);
    GeoPoint middle = new GeoPoint(latMiddle, lonMiddle);

    // Focus "middle"
    mc.setCenter(middle);

    // Retrieve route informations from google:
    // Generate URL for Google Maps query
    final String googleMapsUrl = "http://maps.google.com/maps?f=d&hl=en&saddr="
            + Double.toString(posUser.getLatitudeE6() / 1E6)
            + ","
            + Double.toString(posUser.getLongitudeE6() / 1E6)
            + "&daddr="
            + Double.toString(posCar.getLatitudeE6() / 1E6)
            + ","
            + Double.toString(posCar.getLongitudeE6() / 1E6)
            + "&ie=UTF8&0&om=0&output=kml" // Requested output format:
            + "&dirflg=w"; // Walking mode
    // KML-File
    Log.v("URL", googleMapsUrl);

    // Connect to the Internet and request corresponding KML file
    HttpURLConnection urlConn = null;
    try {
        // Start up a new URL-Connection
        URL url = new URL(googleMapsUrl);
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setDoInput(true); // Needed for Input
        urlConn.setDoOutput(true); // Needed for Output
        urlConn.connect();

        // Parsing the KML file
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(urlConn.getInputStream());

        // Extract the <coordinates> Tag from <GeometryCollection> as
        // String
        String coordString = doc.getElementsByTagName("GeometryCollection")
                .item(0).getFirstChild().getFirstChild().getFirstChild()
                .getNodeValue();

        // Divide the huge string into an string array of coordinates,
        // using
        // " " as separator
        String[] coords = coordString.split(" ");

        String[] lngLat;

        lngLat = coords[0].split(",");
        GeoPoint gpFrom = new GeoPoint(
                (int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double
                        .parseDouble(lngLat[0]) * 1E6));
        GeoPoint gpTo = null;
        for (int i = 1; i < coords.length; i++) {

            lngLat = coords[i].split(",");
            gpTo = new GeoPoint(
                    (int) (Double.parseDouble(lngLat[1]) * 1E6),
                    (int) (Double.parseDouble(lngLat[0]) * 1E6));

            mapView.getOverlays()
                    .add(
                            new PathOverlay(gpFrom, gpTo, Color.RED,
                                    getResources()));

            gpFrom = gpTo;

        }

    } catch (MalformedURLException e) {
        Log.v("Exception", "Generated URL is invalid");
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        Log.v("Exception",
                "Error while parsing the KML file - Config error");
        e.printStackTrace();
    } catch (SAXException e) {
        Log.v("Exception",
                "Error while parsing the KML file - Parser error");
        e.printStackTrace();
    }

    MarkerOverlay pin1 = new MarkerOverlay(posCar, getResources());
    MarkerOverlay pin2 = new MarkerOverlay(posUser, getResources());

    mapView.getOverlays().add(pin1);
    mapView.getOverlays().add(pin2);
    mc.zoomToSpan(Math
            .abs(posCar.getLatitudeE6() - posUser.getLatitudeE6()), Math
            .abs(posCar.getLongitudeE6() - posUser.getLongitudeE6()));

    mapView.invalidate();

}

private class MyLocationListener implements LocationListener {
    int lat;
    int lon;

    @Override
    public void onLocationChanged(Location loc) {
        if (loc != null) {
            lat = (int) (loc.getLatitude() * 1E6);
            lon = (int) (loc.getLongitude() * 1E6);

            posUser = new GeoPoint(lat, lon);
            mapView.invalidate();
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

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

}

The huge part in the middle works great and can be ignored....may the error occur because the mapView is invalidated twice? It seems to me that the onCreate method is not called again.

poeschlorn
so: I figured it out, I have to redraw my overlays in the onLocationChanged() method of the location listener.the onCreate method is called ONCE at the beginning.by sourcing out my code in a seperate method which is called from both ones above, it works great :)i hope someone else can benifit from this ;-)
poeschlorn