2010-05-03 2 views
0

여러지도 활동을 포함하여 일부 Android 앱을 구현 한 후 GPS 수신기의 onLocationChanged() 메소드가 호출 될 때 활동을 새로 고칩니다.활동을 새로 고치는 방법? 지도보기 새로 고침 실패

나는

저장하는 좌표

는 위치 수신기가있을 수 있도록, 글로벌 값을해야 할 것이다 ... 방법으로 새로 고침 새로운 좌표를 표시하는지도 활동을 알 수있는 생각이 없다 그것에 접근하십시오.

내 샘플 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())를 호출 할 수 있습니다

그것은 좋은 것입니다, 그래서보기보기 :: 된 onDraw() 메소드를 사용하여 다시 그릴 것입니다. 이를 사용하려면 코드를 View (예 : MapView), onDraw() 메소드로 이동해야합니다.

+0

이상한 방식으로 내 코드 (아래 참조)가 "오래된"geoPoints를 덮어 쓰지 않습니다 .... 이상하고 이상한 ... – poeschlorn

+0

오버레이 목록에 새 MapView 클래스를 추가해야합니까? – poeschlorn

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 메서드는 처음에 한 번 호출됩니다. 위의 두 가지 모두에서 호출되는 별도의 메서드에서 내 코드를 소싱하여 큰 효과를 얻을 수 있습니다. 나는 다른 누군가가이 기능을 유용하게 사용하기를 바랍니다. ;-) – poeschlorn