我有一张谷歌地图,当用户按下“开始”按钮时按钮,计时器将启动,该计时器将在每10秒后继续获得用户的当前位置,并且将从普及现在的位置绘制折线,直到用户点击“停止跟踪”。按钮。 现在,除了折线之外,我的一切都很好,它根本没有绘制折线。如果我重新按下“开始”'按钮它(将poloyline从prev添加到当前位置,就像我的应用程序将继续添加折线,如果我一直按下开始按钮但我不想这样)。我希望它能够通过计时器画出线而不是按下按钮。
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
Button start,stop,track_record;
GPSTracker gps;
ArrayList<String> cordsList= new ArrayList<String>();
ArrayList<LatLng> MarkerPoints;
ArrayList<Double> arrLat= new ArrayList<Double>();
ArrayList<Double> arrLng = new ArrayList<Double>();
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private final int TIME_INTERVAL = 10000;
Timer timer=new Timer();
double longitude,latitude;
private static LatLng prev = new LatLng(0,0);
int Flag = 0;
static int begin = 0;
private LatLng fixedBegin ;
private LatLng listPoints = new LatLng(0,0);
ArrayList<LatLng> listP= new ArrayList<LatLng>();
Handler m_handler;
Runnable m_handlerTask ;
int t=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
stop = (Button) findViewById(R.id.btn_stop);
track_record = (Button) findViewById(R.id.btn_TR);
// track record activity
track_record.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplication(), "Your Tracking is started now", Toast.LENGTH_SHORT).show();
///////*************************************////////
// create class object
gps = new GPSTracker(MapsActivity.this);
timer.scheduleAtFixedRate(new TimerTask() {
@SuppressLint("DefaultLocale")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
LatLng current = new LatLng(latitude = gps.getLatitude(),longitude = gps.getLongitude());
if (begin == 0) {
fixedBegin = current;
// create marker
MarkerOptions marker = new MarkerOptions().position(fixedBegin).title("Begin ");
// Changing the color babyyy
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// adding marker
mMap.addMarker(marker);
// drawing polyline here
if(Flag==0) //when the first update comes, we have no previous points,hence this
{
prev=current;
Flag=1;
}
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 16);
mMap.animateCamera(update);
mMap.addPolyline((new PolylineOptions())
.add(prev, current).width(6).color(Color.BLUE)
.visible(true));
prev=current;
current = null;
}
begin++;
Log.i("OK", "lat------ " + latitude);
Log.i("OK", "lng-------- " + longitude);
arrLat.add(latitude);
arrLng.add(longitude);
//////////// TRYING ///////////
// And it Worked :D
/*
if(Flag==0) //when the first update comes, we have no previous points,hence this
{
prev=current;
Flag=1;
}
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 16);
mMap.animateCamera(update);
mMap.addPolyline((new PolylineOptions())
.add(prev, current).width(6).color(Color.BLUE)
.visible(true));
prev=current;
current = null;
*/
}
});
}
}, 0, TIME_INTERVAL);
// check if GPS enabled
if (gps.canGetLocation()) {
Log.i("ok", "Mai to hogaya true");
latitude = gps.getLatitude();
longitude = gps.getLongitude();
String longlat = String.valueOf(latitude) + ":" + String.valueOf(longitude);
cordsList.add(longlat);
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Sorry cant get location", Toast.LENGTH_LONG).show();
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
// gps.showSettingsAlert();
}
Log.i("Finall", "Location-> " + cordsList.toString());
}
}
);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Initializing
MarkerPoints = new ArrayList<>();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Toast on stop
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplication(), "Your Tracking is over now, yellow marker shows your destination", Toast.LENGTH_SHORT).show();
/////////
//yaha kaam karna hai abhi
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(gps.getLatitude(), gps.getLongitude())).title("REACHED :D ");
// Changing the color babyyy
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
// adding marker
mMap.addMarker(marker);
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
timer.cancel();
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
// Setting onclick event listener for the map
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// Already two locations
if (MarkerPoints.size() >= 1) {
MarkerPoints.clear();
mMap.clear();
}
// Adding new item to the ArrayList
MarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
if (MarkerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}
// Below ELSE is not used any more due to the fetched location of user TADAAAA xD
else if (MarkerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
mMap.addMarker(options);
// Checks, whether start and end locations are captured
if (MarkerPoints.size() >= 1) {
//>>>> LatLng origin = MarkerPoints.get(0);
LatLng latLng1 = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
LatLng origin = latLng1;
LatLng dest = MarkerPoints.get(0);
// Getting URL to the Google Directions API
String url = getUrl(origin, dest);
Log.d("onMapClick", url.toString());
FetchUrl FetchUrl = new FetchUrl();
// Start downloading json data from Google Directions API
FetchUrl.execute(url);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
}
);
}
private String getUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class FetchUrl extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
Log.d("Background Task data", data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
答案 0 :(得分:0)
检查以下两个功能。
public void Draw_Map(List<LatLng> val) {
if(val.size() > 1) {
mGoogleMap.addPolyline(new PolylineOptions()
.add(val.get(mSource), val.get(mDestination))
.width(8)
.color(Color.BLACK));
mSource++;
mDestination++;
}
}
private void drawFinalPolygon() {
mLatLngList.add(mLatLngList.get(0));
PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.addAll(mLatLngList);
polygonOptions.strokeColor(Color.BLACK);
polygonOptions.strokeWidth(8);
polygonOptions.fillColor(Color.TRANSPARENT);
Polygon polygon = mGoogleMap.addPolygon(polygonOptions);
mGoogleMap.addMarker(new MarkerOptions()
.title("Marker Title here")
.snippet("Hello, I am marker snippet!")
.position(mLatLngList.get(0)));
}
每当位置发生变化时调用Draw_Map()方法,并在用户点击停止跟踪时调用drawFinalPolygon()方法。