Я хотел бы обновить свой вопрос.Cocncept - это клиент и водитель.Когда водитель находится на дороге, место должно быть соответствующим образом обновлено.Трекер на карте работает, но маркеры не перемещаются, и путь ломаной линии остается тем же самым (он не стирается и не устанавливается на текущую позицию перемещения).Мне нужны маркеры для перемещения и полилинии, чтобы установить соответственно.Я реализовал следующую логику ниже: Пожалуйста, помогите
Код:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback,Tracker.LocationCallback {
GoogleMap map;
ArrayList<LatLng> markerPoints;
TextView tvDistanceDuration;
String latpick, latdrop, lngpick, lngdrop;
Marker markerfrom, markerto;
LatLng fromLatLong, toLatLong;
@BindView(R.id.btn_back)
Button btnBack;
@BindView(R.id.txt_title)
TextView txtTitle;
String fromaddress,toaddress,titleone,titletwo;
Tracker tracker;
Polyline polyline;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
tracker = new Tracker(this,this);
try {
if (getIntent() != null) {
latpick = getIntent().getStringExtra("pickuplat");
lngpick = getIntent().getStringExtra("pickuplng");
latdrop = getIntent().getStringExtra("droplat");
lngdrop = getIntent().getStringExtra("droplng");
titleone = getIntent().getStringExtra("titleone");
titletwo = getIntent().getStringExtra("titletwo");
Log.e("LATPICK", latpick);
Log.e("LATPICK", lngpick);
Log.e("LATPICK", latdrop);Log.e("LATPICK", lngdrop);
if(!latpick.equalsIgnoreCase("0")){
}
}
} catch (Exception e) {
e.printStackTrace();
}
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
markerPoints = new ArrayList<LatLng>();
((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
public void getAddressFromLocation(final double latitude, final double longitude,
final Context context) {
Thread thread = new Thread() {
@Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
final String addressone = addressList.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
Log.e("addressone",addressone);
final String city = addressList.get(0).getLocality();
String state = addressList.get(0).getAdminArea();
String country = addressList.get(0).getCountryName();
String postalCode = addressList.get(0).getPostalCode();
String knownName = addressList.get(0).getFeatureName(); // Only if available else return NULL
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
fromaddress = addressone;
markerfrom = map.addMarker(new MarkerOptions()
.position(fromLatLong)
.title(titleone)
.snippet(fromaddress)
.icon(BitmapDescriptorFactory
.defaultMarker(
BitmapDescriptorFactory.HUE_AZURE)));
markerfrom.showInfoWindow();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
Log.e("Address", "Unable connect to Geocoder", e);
}
}
};
thread.start();
}
public void getAddressFromLocation2(final double latitude, final double longitude,
final Context context) {
Thread thread = new Thread() {
@Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
final String addressone = addressList.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
final String city = addressList.get(0).getLocality();
String state = addressList.get(0).getAdminArea();
String country = addressList.get(0).getCountryName();
String postalCode = addressList.get(0).getPostalCode();
String knownName = addressList.get(0).getFeatureName(); // Only if available else return NULL
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e("addressone",addressone);
toaddress = addressone;
markerto = map.addMarker(new MarkerOptions()
.position(toLatLong)
.title(titletwo)
.snippet(toaddress)
.icon(BitmapDescriptorFactory
.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)));
markerto.showInfoWindow();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
Log.e("Address", "Unable connect to Geocoder", e);
}
}
};
thread.start();
}
private String getDirectionsUrl(String pickuplat, String pickuplng, String droplat, String droplng) {
Log.e("TAG", "INSIDE DIRECTIONS");
// Origin of route
String str_origin = "origin=" + latpick + "," + lngpick;
// Destination of route
String str_dest = "destination=" + latdrop + "," + lngdrop;
// 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";
String MY_API_KEY = "API KEY";
// Building the url to the web service This IP, site or mobile application is not authorized to use this API key. Request received from IP address 122.178.84.38, with empty referer
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&key=" + MY_API_KEY;
Log.e("", url);
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();
br.close();
} catch (Exception e) {
Log.d(" while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
if (ActivityCompat.checkSelfPermission(MapActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
googleMap.setMyLocationEnabled(true);
if (googleMap != null) {
googleMap.getUiSettings().setMapToolbarEnabled(false);
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location arg0) {
// if(initialocation==0){
Location newHotSpot = new Location("My Location");
newHotSpot.setLatitude(arg0.getLatitude());
newHotSpot.setLongitude(arg0.getLongitude());
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
// }
}
});
try {
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
@Override
protected void onResume() {
super.onResume();
tracker.connectClient();
}
@Override
protected void onPause() {
super.onPause();
tracker.disConnectClient();
}
@Override
public void onLocationReceived(Location location) {
if(location!=null){
latpick = String.valueOf(location.getLatitude());
lngpick = String.valueOf(location.getLongitude());
Log.e("location receiver","lattidute"+lngpick+" "+latpick);
if (markerfrom!=null){
markerfrom.remove();
} map.clear();
fromLatLong = new LatLng(Double.parseDouble(latpick), Double.parseDouble(lngpick));
markerfrom = map.addMarker(new MarkerOptions()
.position(fromLatLong)
.title(titleone)
.snippet(fromaddress)
.icon(BitmapDescriptorFactory
.defaultMarker(
BitmapDescriptorFactory.HUE_AZURE)));
markerfrom.showInfoWindow();
clearPath();
try {
fromLatLong = new LatLng(Double.parseDouble(latpick), Double.parseDouble(lngpick));
toLatLong = new LatLng(Double.parseDouble(latdrop), Double.parseDouble(lngdrop));
String url = getDirectionsUrl(latpick, lngpick, latdrop, lngdrop);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(fromLatLong, 10));
double lat1 = Double.parseDouble(latpick);
double log1 = Double.parseDouble(lngpick);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat1, log1), 13.0f));
getAddressFromLocation2(Double.parseDouble(latdrop),Double.parseDouble(lngdrop),MapActivity.this);
getAddressFromLocation(Double.parseDouble(latpick),Double.parseDouble(lngdrop),MapActivity.this);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
// tracker.stopLocationUpdates();
}
private void clearPath() {
if (polyline != null)
polyline.remove();
polyline = null; }
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
@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]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if (result.size() < 1) {
Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) { // Get distance from the list
distance = (String) point.get("distance");
continue;
} else if (j == 1) { // Get duration from the list
duration = (String) point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(4);
lineOptions.color(Color.RED);
}
map.addPolyline(lineOptions);
}
}
}