아직 안드로이드에 익숙해졌으며 Google지도에서 순환했던 경로를 그리는 앱을 만들려고합니다. 나는 성공적으로지도를 표시하고이 코드를 사용하여 두 개의 좌표 사이에 간단한 폴리 라인을 그릴 수 있습니다 다음 'LocationChanged'방법에 위치한 코드 조각을 만들 만들 내가 해봤Android, 폴리 라인을 사용하여지도에 자전거 타기를 그리거나 인쇄하려고합니다.
//Draws a thin red line from London to New York.
Polyline line = googlemap.addPolyline(new PolylineOptions()
.add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
.width(5)
.color(Color.RED));
을하는 I 가정은 위치가 변경 될 때마다 호출되며 앱이 열리 자마자 (코드 하단에있는 메소드) 바로 시작됩니다. 그것은 현재 위치 좌표를 취하고 이전의 현재 위치 좌표와 그것들 사이에 폴리 선을 그립니다.
토큰을 위치 변경 메서드에 추가 했으므로 실행되는 시점을 볼 수 있습니다. 그래서 코드에 문제가있는 것 같아서 실행되지 않습니다. . (I는 GPS 신호 야외 응용 프로그램을 테스트 한이 선을 그어야하지 않습니다)
는 (응용 프로그램은 오류없이 실행되지만 선 그리기하지 않습니다) 내가 어떤 도움을 찾고 있어요
을 응용 프로그램에서 선을 그어주는 데 도움이 될 것입니다.
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
public class Record_screen_activity extends FragmentActivity implements
LocationListener, OnClickListener {
GoogleMap googlemap, draw;
Location currentLocation;
Location myLocation2;
Button sqlUpdate, sqlView, sqlModify, sqlLoad, sqlDelete, startChrono, pauseChrono;
EditText sqlNotes, sqlRouteName, sqlLocation, sqlRow;
TextView sqlDate;
Chronometer sqlChrono;
long time = 0;
int drawing = 1;
//add above here ===========================================================
// above I am declaring the references that I will use in this file they are
// linked below to the
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.record_screen); // Names the layout file which
// is linked to this activity
startChrono = (Button) findViewById(R.id.b_Start);
pauseChrono = (Button) findViewById(R.id.b_Pause);
startChrono.setOnClickListener(this);
pauseChrono.setOnClickListener(this);
sqlUpdate = (Button) findViewById(R.id.bSQL_Update);
sqlRouteName = (EditText) findViewById(R.id.etSQL_RouteName);
sqlLocation = (EditText) findViewById(R.id.etSQL_Location);
sqlNotes = (EditText) findViewById(R.id.etSQL_Notes);
sqlChrono = (Chronometer) findViewById(R.id.c_Timer);
sqlDate = (TextView) findViewById(R.id.tv_Date);
//add above here ===========================================================
// the above lines link the buttons and EditText fields from the xml
// Layout file to the references stated at the top of this file
sqlView = (Button) findViewById(R.id.bSQL_View);
sqlView.setOnClickListener(this);
sqlUpdate.setOnClickListener(this);
sqlRow = (EditText) findViewById(R.id.etSQL_Rowid);
sqlModify = (Button) findViewById(R.id.bSQL_Modify);
sqlLoad = (Button) findViewById(R.id.bSQL_Load);
sqlDelete = (Button) findViewById(R.id.bSQL_Delete);
// above references link buttons and tv's to the actual buttons and tv's
// in th xml file
sqlModify.setOnClickListener(this);
sqlLoad.setOnClickListener(this);
sqlDelete.setOnClickListener(this);
SupportMapFragment mf = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mvMain);
googlemap = mf.getMap();
googlemap.setMyLocationEnabled(true);
googlemap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); // map tiles type can
// be changed here
// i.e. to satalite
// view
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager
.getLastKnownLocation(locationManager.getBestProvider(criteria,
false));
if (location != null) {
googlemap
.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location
.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location
.getLongitude())) // Sets the center of the map to
// location user
.zoom(17) // Sets the zoom
.bearing(0) // Sets the orientation of the camera to east
.tilt(0) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
googlemap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
currentLocation = location;
}
// Add a thin red line from London to New York.
// Polyline line = googlemap.addPolyline(new PolylineOptions()
// .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
// .width(5)
//.color(Color.RED));
// Add a thin red line from London to New York.
//setting the date
int yy;
int mm;;
int dd;
final Calendar c = Calendar.getInstance();
yy = c.get(Calendar.YEAR);
mm = c.get(Calendar.MONTH);
dd = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
sqlDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(dd).append("").append("/").append(mm + 1).append("/")
.append(yy));
}
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.b_Start:
sqlChrono.setBase(SystemClock.elapsedRealtime() + time); //mabe get rid of nanos
sqlChrono.start();
Dialog d = new Dialog(this);
d.setTitle("Route Now Recording"); // sets the dialog box with
// success message
TextView tv = new TextView(this);
tv.setText("Please Lock your Screen");
d.setContentView(tv);
d.show();
//sets these variables before the loop is run
break;
case R.id.b_Pause:
time = sqlChrono.getBase() - SystemClock.elapsedRealtime();
sqlChrono.stop();
drawing = 1;
break;
}
// ===============================================
// ================Update(save) button============
// ===============================================
switch (arg0.getId()) {
case R.id.bSQL_Update:
boolean didItWork = true;
try {
String routename = sqlRouteName.getText().toString();
String location = sqlLocation.getText().toString();
String notes = sqlNotes.getText().toString();
String chrono = sqlChrono.getText().toString();
String date = sqlDate.getText().toString();
//add above here ===========================================================
SQL_management_activity entry = new SQL_management_activity(
Record_screen_activity.this);
entry.open();
entry.createEntry(routename, location, notes, chrono, date);
//add above here ===========================================================
entry.close();
} catch (Exception e) {
didItWork = false;
String error = e.toString();// the error string will be printed
// to the dialog box to display the
// error code to the user
Dialog d = new Dialog(this);
d.setTitle("Error ohh no..."); // sets the diaog box with
// success mesasge
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
} finally {
if (didItWork) {
// didItWork = true;
Dialog d = new Dialog(this);
d.setTitle("Saving Route"); // sets the diaog box with
// success mesasge
TextView tv = new TextView(this);
tv.setText("Status: Success");
d.setContentView(tv);
d.show();
Thread timer = new Thread() { // this is the same timer as
// on the spalshcren
public void run() { // it automaticaly moves to the
// review page after 500 miliseconds
try {
sleep(1000); // duration the splash screen is
// displayed for
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//Intent openMain_menu = new Intent(
// "com.hew235.mapapp.REVIEW_SCREEN_ACTIVITY");
// startActivity(openMain_menu);
}
}
};
timer.start();
}
}
break;
// ===============================================
// ==================View button================== the end of tutorial
// 18 will help make a main menu button
// ===============================================
case R.id.bSQL_View: // opens the view page
Intent i = new Intent("com.hew235.mapapp.REVIEW_SCREEN_ACTIVITY");
startActivity(i);
break;
// ===============================================
// ==================Load button==================
// ===============================================
case R.id.bSQL_Load:
boolean didItWork2 = true;
try {
String s = sqlRow.getText().toString();// this string will
// return whatever is in
// the edit text
long l = Long.parseLong(s);// converts whatever is in the above
// string into a long type variable
SQL_management_activity sma = new SQL_management_activity(this);
sma.open();
String returnedRoutename = sma.getRoutename(l);// method
String returnedLocation = sma.getLocation(l);// method
String returnedNotes = sma.getNotes(l);// method
String returnedChrono = sma.getChrono(l);// method
String returnedDate = sma.getDate(l);// method
//add above here ===========================================================
sma.close();
sqlRouteName.setText(returnedRoutename);
sqlLocation.setText(returnedLocation);
sqlNotes.setText(returnedNotes);
sqlChrono.setText(returnedChrono);
sqlDate.setText(returnedDate);
//add above here ===========================================================
} catch (Exception e) {
didItWork2 = false;
String error = e.toString();// the error string will be printed
// to the dialog box to display the
// error code to the user
Dialog d = new Dialog(this);
d.setTitle("Error ohh no..."); // sets the diaog box with
// success mesasge
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
} finally {
if (didItWork2) {
// didItWork = true;
Dialog d = new Dialog(this);
d.setTitle("Loading Data"); // sets the diaog box with
// success mesasge
TextView tv = new TextView(this);
tv.setText("Status: Success");
d.setContentView(tv);
d.show();
}
}
break;
// ===============================================
// ==================Modify button================
// ===============================================
case R.id.bSQL_Modify:
boolean didItWork4 = true;
try {
String sRow = sqlRow.getText().toString();
String mRoutename = sqlRouteName.getText().toString();
String mLocation = sqlLocation.getText().toString();
String mNotes = sqlNotes.getText().toString();
String mChrono = sqlChrono.getText().toString();
String mDate = sqlDate.getText().toString();
//add above here ===========================================================
long lRow = Long.parseLong(sRow);
SQL_management_activity ex = new SQL_management_activity(this);
ex.open();
ex.updateEntry(lRow, mRoutename, mLocation, mNotes, mChrono, mDate); // these are the
// fields that
// are being
// updated
//add above here ===========================================================
ex.close();
} catch (Exception e) {
didItWork4 = false;
String error = e.toString();// the error string will be printed
// to the dialog box to display the
// error code to the user
Dialog d = new Dialog(this);
d.setTitle("Error ohh no..."); // sets the diaog box with
// success mesasge
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
} finally {
if (didItWork4) {
// didItWork = true;
Dialog d = new Dialog(this);
d.setTitle("Modifying Record"); // sets the diaog box with
// success mesasge
TextView tv = new TextView(this);
tv.setText("Status: Success");
d.setContentView(tv);
d.show();
Thread timer = new Thread() { // this is the same timer as//
// on the spalshcren
public void run() { // it automaticaly moves to the//
// review page after 500 miliseconds
try {
sleep(1200); // duration the splash screen is//
// displayed for
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Intent openMain_menu = new Intent(
"com.hew235.mapapp.REVIEW_SCREEN_ACTIVITY");
startActivity(openMain_menu);
}
}
};
timer.start();
}
}
break;
// ===============================================
// ==================Delete button================
// ===============================================
case R.id.bSQL_Delete:
boolean didItWork3 = true;
try {
String sRow1 = sqlRow.getText().toString();
long lRow1 = Long.parseLong(sRow1);
SQL_management_activity ex1 = new SQL_management_activity(this);
ex1.open();
ex1.deleteEntry(lRow1);
ex1.close();
} catch (Exception e) {
didItWork3 = false;
String error = e.toString();// the error string will be printed
// to the dialog box to display the
// error code to the user
Dialog d = new Dialog(this);
d.setTitle("Error ohh no..."); // sets the diaog box with
// success mesasge
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
} finally {
if (didItWork3) {
// didItWork = true;
Dialog d = new Dialog(this);
d.setTitle("Deleting Record"); // sets the diaog box with
// success mesasge
TextView tv = new TextView(this);
tv.setText("Status: Success");
d.setContentView(tv);
d.show();
Thread timer = new Thread() { // this is the same timer as
// on the spalshcren
public void run() { // it automaticaly moves to the
// review page after 500 miliseconds
try {
sleep(1200); // duration the splash screen is
// displayed for
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Intent openMain_menu = new Intent(
"com.hew235.mapapp.REVIEW_SCREEN_ACTIVITY");
startActivity(openMain_menu);
}
}
};
timer.start();
}
}
break;
}
}
private static MapController getController() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map1_screen_activity, menu);
GoogleMap map;
return true;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
CharSequence text = "Hello toast! r u hungry";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location1 = locationManager
.getLastKnownLocation(locationManager.getBestProvider(criteria,
false));
if (location1 != null) {
googlemap
.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location1.getLatitude(), location1
.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location1.getLatitude(), location1
.getLongitude())) // Sets the center of the map to
// location user
.zoom(17) // Sets the zoom
.bearing(0) // Sets the orientation of the camera to east
.tilt(0) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
googlemap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
location1 = currentLocation;
}
currentLocation = myLocation2;
Polyline line = googlemap.addPolyline(new PolylineOptions()
.add(new LatLng (myLocation2.getLatitude(), myLocation2
.getLongitude()),
new LatLng (currentLocation.getLatitude(), currentLocation
.getLongitude()))
.width(5)
.color(Color.RED));
currentLocation = myLocation2; //sets the location variables ready for the lines to join the dots
}
@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
Context context = getApplicationContext();
CharSequence text = "status changed";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
전체 클래스가 아닌 관련 코드 만 포함하십시오. – tyczj
[docs] (https://developer.android.com/training/location/receive-location-updates.html) 위치 수신 방법을 확인하십시오. 업데이트. –
감사합니다. LucationUpdates 설명서를 살펴보고 필요한 업데이트 기능이있는 샘플 앱을 발견했습니다. – user3480901