0
I have the following code that creates a route using the Google Maps Directions API:
public class MapsActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback {
private LatLng position;
private Polyline polyline;
private List<LatLng> list;
private long distance;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
pegarLocalização();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
limparMapa();
adicionarLocal();
adicionarDestino(latLng);
pegarLocalização();
getRoute(position, latLng);
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
if(marker.getTitle().isEmpty()) {
return false;
} else {
return true;
}
}
});
}
public void adicionarLocal() {
mMap.addMarker(new MarkerOptions()
.position(position)
.title("Sua Localização"));
CameraPosition cp = new CameraPosition.Builder().target(position).zoom(15).build();
CameraUpdate cu = CameraUpdateFactory.newCameraPosition(cp);
mMap.moveCamera(cu);
}
public void adicionarDestino(LatLng position) {
// Add a marker in Sydney and move the camera
mMap.addMarker(new MarkerOptions()
.position(position)
.title(""));
CameraPosition cp = new CameraPosition.Builder().target(position).zoom(10).build();
CameraUpdate cu = CameraUpdateFactory.newCameraPosition(cp);
mMap.moveCamera(cu);
}
public void limparMapa() {
mMap.clear();
}
public void pegarLocalização() {
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}, 0);
if (ContextCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(getBaseContext(), "Você já negou antes essa permissão! \nPara saber a sua localização necessitamos dessa permissão!", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}, 0);
} else {
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}, 0);
}
}else {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ContextCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
position = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
adicionarLocal();
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(getBaseContext(), "Conexão falhou!", Toast.LENGTH_LONG).show();
}
//-------------------------------------------------ROTA-------------------------------------------------
public void drawRoute(){
PolylineOptions po;
if(polyline == null){
po = new PolylineOptions();
for(int i = 0; i < list.size(); i++){
po.add(list.get(i));
}
po.color(Color.BLACK).width(4);
polyline = mMap.addPolyline(po);
}
else{
polyline.setPoints(list);
}
}
// WEB CONNECTION
public void getRoute(final LatLng origin, final LatLng destination){
new Thread(){
public void run(){
String url= "http://maps.googleapis.com/maps/api/directions/json?" +
"origin=" + origin.latitude + "," + origin.longitude +
"&destination=" + destination.latitude+","+destination.longitude +
"&sensor=false";
HttpResponse response;
HttpGet request;
AndroidHttpClient client = AndroidHttpClient.newInstance("route");
request = new HttpGet(url);
try {
response = client.execute(request);
final String answer = EntityUtils.toString(response.getEntity());
runOnUiThread(new Runnable(){
public void run(){
try {
list = buildJSONRoute(answer);
drawRoute();
}
catch(JSONException e) {
e.printStackTrace();
}
}
});
}
catch(IOException e) {
e.printStackTrace();
}
}
}.start();
}
// PARSER JSON
public List<LatLng> buildJSONRoute(String json) throws JSONException{
JSONObject result = new JSONObject(json);
JSONArray routes = result.getJSONArray("routes");
distance = routes.getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getInt("value");
JSONArray steps = routes.getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONArray("steps");
List<LatLng> lines = new ArrayList<LatLng>();
for(int i=0; i < steps.length(); i++) {
String polyline = steps.getJSONObject(i).getJSONObject("polyline").getString("points");
for(LatLng p : decodePolyline(polyline)) {
lines.add(p);
}
}
return(lines);
}
// DECODE POLYLINE
private List<LatLng> decodePolyline(String encoded) {
List<LatLng> listPoints = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5)));
Log.i("Script", "POL: LAT: "+p.latitude+" | LNG: "+p.longitude);
listPoints.add(p);
}
return listPoints;
}
}
However it only works the first time, if I close and open the application it works again, then stops working.
Anyone can help?