2010-05-03 112 views
0

在實施一些Android應用程序(包括幾個Map活動)後,我嘗試在GPS偵聽器的onLocationChanged()方法被調用時刷新活動。如何刷新活動?地圖視圖刷新失敗

我不知道如何告訴地圖活動自行刷新並顯示新COORDS ...

的COORDS存儲將成爲全球值,這樣位置監聽器將有訪問它。

在我的示例GPS類(請參閱下面的代碼)我只是改變了文本視圖的文本....但如何在地圖視圖中做到這一點?

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

我覺得這個問題的解決不會很困難,但我只需要開始;-)

這整個程序應像一個非常簡單的導航系統正常工作。

這將是巨大的,如果有人可以幫助我一點點進一步:)

回答

5

你可以調用查看::無效()(http://developer.android.com/reference/android/view/View.html#invalidate()),因此視圖將重繪使用View ::的onDraw()方法。要使用它,你應該將你的代碼移動到一個視圖(例如MapView),它的onDraw()方法。

+0

以一種奇怪的方式我的代碼(見下文)不覆蓋「舊」geoPoints ....奇怪,奇怪... – poeschlorn 2010-05-04 12:02:34

+0

我必須將新的MapView類添加到疊加列表嗎? – poeschlorn 2010-05-04 12:35:51

0

感謝您的回答,理論上聽起來不錯。但我找回我的地圖沒有更新...的評論功能提供了小空間我的代碼,這就是爲什麼我在這裏張貼:

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

} 

中間的很大一部分的偉大工程,可以忽略不計。 ...可能會發生錯誤,因爲mapView被無效兩次? 在我看來,onCreate方法不會再次調用。

+1

所以:我想通了,我必須在位置偵聽器的onLocationChanged()方法中重繪我的覆蓋。 onCreate方法在開始時稱爲ONCE。 通過從我的代碼中分離出一個獨立的方法,從上面的兩個代碼中調用它,它工作的很棒:) 我希望別人能夠從這方面受益;-) – poeschlorn 2010-05-05 11:48:21