there! I am a brand new learner of android and geocoding. And I wonder how I can display the current address rather than showing the "Here you are" message. I know I was supposed to use the getFromLocation() method to accomplish my goal. However, I do not know how I can do that and where to put it.
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private final int REQUEST_LOCATION_PERMISSIONS = 0;
private float mZoomLevel = 15;
private GoogleMap mMap;
private FusedLocationProviderClient mClient;
private LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
#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);
// Create location request
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mClient = LocationServices.getFusedLocationProviderClient(this);
// Create location callback
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
for (Location location : locationResult.getLocations()) {
updateMap(location);
}
}
}
};
mClient = LocationServices.getFusedLocationProviderClient(this);
}
private void updateMap(Location location) {
// Get current location
LatLng myLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
// Place a marker at the current location
MarkerOptions myMarker = new MarkerOptions()
.title("Here you are!")
.position(myLatLng);
// Remove previous marker
mMap.clear();
// Add new marker
mMap.addMarker(myMarker);
// Move and zoom to current location at the street level
CameraUpdate update = CameraUpdateFactory.
newLatLngZoom(myLatLng, mZoomLevel);
mMap.animateCamera(update);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
CameraPosition cameraPosition = mMap.getCameraPosition();
mZoomLevel = cameraPosition.zoom;
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this,"Lat: " + marker.getPosition().latitude +
"\nLong: " + marker.getPosition().longitude, Toast.LENGTH_LONG).show();
return false;
}
});
}
#Override
public void onPause() {
super.onPause();
mClient.removeLocationUpdates(mLocationCallback);
}
#SuppressLint("MissingPermission")
#Override
public void onResume() {
super.onResume();
if (hasLocationPermission()) {
mClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
}
}
private boolean hasLocationPermission() {
// Request fine location permission if not already granted
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this ,
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQUEST_LOCATION_PERMISSIONS);
return false;
}
return true;
}
}
I was trying to add the following to the code to change the message to a specific location:
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
updateMap(location);
} catch (Exception e) {
e.printStackTrace();
}
}
getFromAddress method return list of possible address.you can get full address like bellow code.
List<Address> fromLocation = geocoder.getFromLocation(location.latitude, location.longitude, 1);
Address address = fromLocation.get(0);
String zipCode = address.getPostalCode());
String city = address.getLocality();
String subAdmin = address.getSubAdminArea();
String countryCode = address.getCountryCode());
String state = address.getAdminArea());
Also you can update your marker as bellow
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.draggable(true);
markerOptions.position(latLng);
markerOptions.title(city);// your text put here
map.addMarker(markerOptions);
Related
I am trying to make a marker that displays the users current location, but my app is always crashing. By debugging, I know that "here" which is where i store the users latitude and longtitude is always null throughout the program.
Heres the java code, I am simply trying to get the current location when the activity is created.
package com.example.mobileproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.CancellationTokenSource;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.maps.model.PlacesSearchResult;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class activity_hospitals extends FragmentActivity implements OnMapReadyCallback {
Toolbar mytoolbar;
GoogleMap Gmap;
FusedLocationProviderClient flsc;
public LatLng here;
public double longo, lato;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospitals);
mytoolbar = (Toolbar) findViewById(R.id.hospitalToolbar);
mytoolbar.setTitle("Hospitals Near You");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
flsc = LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Gmap = googleMap;
LatLng temp = here;
LatLng here = new LatLng(33.71456158807447, 35.48425016137045);
Gmap.addMarker(new MarkerOptions().position(here).title("Your Location"));
LatLng placeholder1 = new LatLng(33.66535378588594, 35.420147180348465);
Gmap.addMarker(new MarkerOptions().position(placeholder1).title("Dr. Monzer al Haj Hospital"));
LatLng placeholder2 = new LatLng(33.76696201016636, 35.48301133270906);
Gmap.addMarker(new MarkerOptions().position(placeholder2).title("SSH"));
float zoomLevel = 11.0f; //This goes up to 21
Gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(here, zoomLevel));
}
public void getLastLocation(){
/*
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
flsc.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location!=null){
Geocoder geocoder = new Geocoder(activity_hospitals.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
Double lat = addresses.get(0).getLatitude(), lon = addresses.get(0).getLongitude();
here = new LatLng(lat, lon);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
else{
askPermission();
}*/
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
flsc.getLastLocation().addOnSuccessListener(this, location -> {
if (location != null) {
longo = location.getLatitude();
lato = location.getLongitude();
here = new LatLng(lato, longo);
}
});
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
private void askPermission() {
ActivityCompat.requestPermissions(activity_hospitals.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 100){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
getLastLocation();
}
else{
Toast.makeText(this, "Required Permission", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
I tried several youtube videos that all used the same code. I then tried googling it, but the codes I found didnt work either.
The reason "here" is always null could be because you try to use it before the location actually arrived. Try commenting onMapReady() method, and just print your location inside addOnSuccessListener. If that works, than you just have to find a way how to wait for the location to arrive and then show it on the map.
I am trying to get my location in a separate class (functions.java) that can be called in from the MainActivity. I am using intent to get the data back to the MainActivity. I had the function getCurrentGPSLocation() in my MainActivity first and it worked fine, but I needed to put it into a separate class as I want to use it for a foreground service as well.
The LocationRequest works, but I have found out that the LocationCallback does not work as everything belonging to the LocationCallback is ignored (I checked it by putting the string ser_Location = "London"; in and outside the brackets of the LocationCallback.) So I do not get any location result.
Where is my mistake in the code?
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Looper;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class Functions extends AppCompatActivity {
//initialize variable
FusedLocationProviderClient fusedLocationProviderClient;
private double ser_Latitude;
private double ser_Longitude;
private String ser_Accuracy;
private String ser_Altitude;
private String currentDateandTime;
private String ser_Location;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Boolean precision = getIntent().getBooleanExtra("precision", true);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(
Functions.this);
getCurrentGPSLocation();
Intent intent = new Intent();
intent.putExtra("latitude", ser_Latitude);
intent.putExtra("longitude", ser_Longitude);
intent.putExtra("accuracy", ser_Accuracy);
intent.putExtra("altitude", ser_Altitude);
intent.putExtra("location", ser_Location);
intent.putExtra("currentDateandTime", currentDateandTime);
setResult(RESULT_OK, intent);
Functions.this.finish();
}
//Force new GPS Location Request
private void getCurrentGPSLocation() {
// get the new location from the fused client
// update the UI - i.e. set all properties in their associated text view items
//Initialize new location request
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(3000)
.setFastestInterval(2000)
.setNumUpdates(1)
;
//Initialize location call back
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
//Initialize location1
Location location1 = locationResult.getLastLocation();
//Set latitude
ser_Latitude = location1.getLatitude();
//Set longitude
ser_Longitude = location1.getLongitude();
//Set Accuracy
double ser_accura1 = location1.getAccuracy();
ser_Accuracy = new DecimalFormat("##.##").format(ser_accura1) + " m";
//Set Altitude
double ser_altit1 = location1.getAltitude();
ser_Altitude = new DecimalFormat("##.##").format(ser_altit1) + " m";
//Get Adress
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(ser_Latitude, ser_Longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
String _Location1 = listAddresses.get(0).getAddressLine(0);
//Set Location
//ser_Location = String.valueOf(_Location1);
}
} catch (IOException e) {
e.printStackTrace();
}
ser_Location = "London";
//Set Update Time
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy 'um ' HH:mm:ss z");
currentDateandTime = sdf.format(new Date());
}
};
//Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest
, locationCallback, Looper.myLooper());
}
}
Thanks to the comments I can now get the intent to the MainActivity with the following code, having put the intent into the onResult part:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class Functions extends AppCompatActivity {
//initialize variable
FusedLocationProviderClient fusedLocationProviderClient;
private double ser_Latitude;
private double ser_Longitude;
private String ser_Accuracy;
private String ser_Altitude;
private String currentDateandTime;
private String ser_Location;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Boolean precision = getIntent().getBooleanExtra("precision", true);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(
Functions.this);
getCurrentGPSLocation();
/* Intent intent = new Intent();
intent.putExtra("latitude", ser_Latitude);
intent.putExtra("longitude", ser_Longitude);
intent.putExtra("accuracy", ser_Accuracy);
intent.putExtra("altitude", ser_Altitude);
intent.putExtra("location", ser_Location);
intent.putExtra("currentDateandTime", currentDateandTime);
setResult(RESULT_OK, intent);
Functions.this.finish();*/
}
//Force new GPS Location Request
private void getCurrentGPSLocation() {
// get the new location from the fused client
// update the UI - i.e. set all properties in their associated text view items
//Initialize new location request
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(3000)
.setFastestInterval(2000)
.setNumUpdates(3)
;
Log.d("LocationRequest", "Request done");
//Initialize location call back
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Log.d("LocationCallback", "Callback started");
//Initialize location1
Location location1 = locationResult.getLastLocation();
//Set latitude
ser_Latitude = location1.getLatitude();
//Set longitude
ser_Longitude = location1.getLongitude();
//Set Accuracy
double ser_accura1 = location1.getAccuracy();
ser_Accuracy = new DecimalFormat("##.##").format(ser_accura1) + " m";
//Set Altitude
double ser_altit1 = location1.getAltitude();
ser_Altitude = new DecimalFormat("##.##").format(ser_altit1) + " m";
//Get Adress
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(ser_Latitude, ser_Longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
String _Location1 = listAddresses.get(0).getAddressLine(0);
//Set Location
//ser_Location = String.valueOf(_Location1);
}
} catch (IOException e) {
e.printStackTrace();
}
ser_Location = "London";
//Set Update Time
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy 'um ' HH:mm:ss z");
currentDateandTime = sdf.format(new Date());
Toast.makeText(getApplicationContext(),Double.toString(ser_Longitude),Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("latitude", ser_Latitude);
intent.putExtra("longitude", ser_Longitude);
intent.putExtra("accuracy", ser_Accuracy);
intent.putExtra("altitude", ser_Altitude);
intent.putExtra("location", ser_Location);
intent.putExtra("currentDateandTime", currentDateandTime);
setResult(RESULT_OK, intent);
Functions.this.finish();
}
};
//Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest
, locationCallback, Looper.myLooper());
}
}
Now onLocationResult happens three times when I set the NumUpdates to 3 to get a higher precision (I can see that in the toast messages with the longitude and in the Log Callback started). I want to have the last update result being handed over. This version hands over the result of the first location update. So this is only half of the solution.
And it returns the following warning: Skipped 55 frames! The application may be doing too much work on its main thread. However, this could be a completely different problem, so don't worry too much about it.
So, here we go - I found a solution for the last problem. I added a counter and made the intent be triggered when the counter reaches the number of requested location updates. Now everything works fine.
Thanks for your help!
package com.example.currentlocation;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class Functions extends AppCompatActivity {
private static final int NUM_UPDATES = 8;
//initialize variable
FusedLocationProviderClient fusedLocationProviderClient;
private double ser_Latitude;
private double ser_Longitude;
private String ser_Accuracy;
private String ser_Altitude;
private String currentDateandTime;
private String ser_Location;
int i = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Boolean precision = getIntent().getBooleanExtra("precision", true);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(
Functions.this);
getCurrentGPSLocation();
}
//Force new GPS Location Request
private void getCurrentGPSLocation() {
// get the new location from the fused client
// update the UI - i.e. set all properties in their associated text view items
//Initialize new location request
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(2500)
.setFastestInterval(1500)
.setNumUpdates(NUM_UPDATES)
;
Log.d("LocationRequest", "Request done");
//Initialize location call back
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Log.d("LocationCallback", "Callback started");
//Initialize location1
Location location1 = locationResult.getLastLocation();
//Set latitude
ser_Latitude = location1.getLatitude();
//Set longitude
ser_Longitude = location1.getLongitude();
//Set Accuracy
double ser_accura1 = location1.getAccuracy();
ser_Accuracy = new DecimalFormat("##.##").format(ser_accura1) + " m";
//Set Altitude
double ser_altit1 = location1.getAltitude();
ser_Altitude = new DecimalFormat("##.##").format(ser_altit1) + " m";
//Get Adress
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(ser_Latitude, ser_Longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
String _Location1 = listAddresses.get(0).getAddressLine(0);
//Set Location
ser_Location = String.valueOf(_Location1);
}
} catch (IOException e) {
e.printStackTrace();
}
//Set Update Time
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy 'um ' HH:mm:ss z");
currentDateandTime = sdf.format(new Date());
Toast.makeText(getApplicationContext(),ser_Accuracy,Toast.LENGTH_SHORT).show();
if (i==NUM_UPDATES) {
Intent intent = new Intent();
intent.putExtra("latitude", ser_Latitude);
intent.putExtra("longitude", ser_Longitude);
intent.putExtra("accuracy", ser_Accuracy);
intent.putExtra("altitude", ser_Altitude);
intent.putExtra("location", ser_Location);
intent.putExtra("currentDateandTime", currentDateandTime);
setResult(RESULT_OK, intent);
Functions.this.finish();}
else {i++;}
}
};
//Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest
, locationCallback, Looper.myLooper());
}
}
I'm quite new to android development and I was wondering if it is possible for me to locate the nearest marker to a user and knowing which marker is closest direct the user there using a polyline and google directions api. The locations of the markers are taken from a database that I have parsed into a list array which I then use to place the markers on the map. I have tried to find help from other questions however they do not seem to fit in my project.
If it is possible for me to find the nearest marker to the user how can I do it if not is there an alternative method I could use??
This is my code for my main activity:
package com.example.defiblocator;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
public static TextView data;
public static String location;
GoogleMap mapAPI;
SupportMapFragment mapFragment;
Location mLastLocation;
Marker mCurrLocationMarker;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
String delimiter = ",";
List<String> full = new ArrayList<>();
List<String> size = new ArrayList<>();
private ArrayList<LatLng> markerCoords = new ArrayList<LatLng>();
String info;
String name;
Double lat;
Double lng;
Button emergency;
LatLng mark;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapAPI);
mapFragment.getMapAsync(this);
data = findViewById(R.id.fetchdata);
new fetchData(new CallbackClass()).execute();
emergency = findViewById(R.id.button);
emergency.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mapAPI = googleMap;
mapAPI.getUiSettings().setZoomControlsEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mapAPI.setMyLocationEnabled(true);
//mapAPI.setOnMyLocationChangeListener(this);
}
} else {
buildGoogleApiClient();
mapAPI.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
/*mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}*/
//Place current location marker
LatLng patient = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(patient);
markerOptions.title("Patient");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mCurrLocationMarker = mapAPI.addMarker(markerOptions);
//move map camera
mapAPI.animateCamera(CameraUpdateFactory.zoomTo(11));
mapAPI.moveCamera(CameraUpdateFactory.newLatLng(patient));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public class CallbackClass implements CallbackInterface {
#Override
public void onSuccess(String callbackData) {
info = callbackData;
full = Arrays.asList(info.split(delimiter));
size = Arrays.asList(info.split(delimiter));
Integer x = 0;
while(x != size.size()){
name = full.get(x);
x += 1;
lat = Double.valueOf(full.get(x));
x += 1;
lng = Double.valueOf(full.get(x));
x += 1;
LatLng pos = new LatLng(lat, lng);
mapAPI.addMarker(new MarkerOptions().position(pos).title(name));
mark = new LatLng(lat,lng);
markerCoords.add(mark);
}
}
#Override
public void onFailure() {
}
}
}
and this is the code for parsing the JSON from the database any help would be greatly appreciated.
package com.example.defiblocator;
import android.app.Application;
import android.os.AsyncTask;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask <Void,Void,Void>{
CallbackInterface callbackInterface;
String data = "";
String json_url;
String singleParsed = "";
public String dataParsed = "";
String sent;
public fetchData(CallbackInterface callbackInterface) {
this.callbackInterface = callbackInterface;
}
public Integer x = 0;
#Override
protected void onPreExecute(){
json_url = "http://defiblocator.ml/json_get_data.php";
dataParsed = "";
}
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for(int i =0 ; i <JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = JO.get("name") + "," + JO.get("lat") + "," +JO.get("lng") + "," ;
dataParsed = dataParsed + singleParsed ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException | JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
MainActivity.data.setText(dataParsed);
callbackInterface.onSuccess(dataParsed);
}
}
You could use a simple distance formula to archive this:
private Double distance(Double lat1, Double lon1, Double lat2, Double lon2) {
return Math.sqrt (Math.pow((lat1 - lat2), 2) - Math.pow((lon1 - lon2), 2));
}
// The user Location
currentLat = xxxx;
currentLon = xxxx;
if ((markerCoords != null) && (markerCoords.size() > 0)) {
LatLng near = markerCoords.get(0);
for (int x = 1; x < markerCoords.size(); x++) {
Double lat = markerCoords.get(x).latitude;
Double lon = markerCoords.get(x).longitude;
Double currentMarkerdistance = distance(
currentLat,
currentLon,
markerCoords.get(x).latitude,
markerCoords.get(x).longitude);
Double nearMarkerdistance = distance(
currentLat,
currentLon,
near.latitude,
near.longitude);
if (currentMarkerdistance < nearMarkerdistance) {
near = markerCoords.get(x);
}
}
}
// After this process the near variable will hold the near marker
In this code, I need to send name and number to the location database with the map's long and lat. Marker's long and lat sending to the firebase without any issue but name and number not sending to the firebase. I cannot find the issue of the code because in the logcat there are not showing any issue. Can you please help me to fix this.
package com.example.policeemergencysystem;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;
import android.os.Build;
import android.os.Bundle;
import com.example.policeemergencysystem.Prevelant.Prevelant;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.policeemergencysystem.Model.AdminOrders;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.policeemergencysystem.Prevelant.Prevelant;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
private GoogleMap mMap;
private Button doneBtn;
TextView backBtn;
Marker myMarker;
LocationManager locationManager;
private static final String TAG = "MainActivity";
private String name;
private String userID = "", userNAME = "", userPHONE = "";
DatabaseReference ordersRef = FirebaseDatabase.getInstance().getReference()
.child("Location")
.child(Prevelant.currentOnlineUser.getUsername());
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
doneBtn = (Button) findViewById(R.id.doneBtn);
backBtn = (TextView) findViewById(R.id.backBtn);
userID = getIntent().getStringExtra("uid");
userNAME = getIntent().getStringExtra("uname");
userPHONE = getIntent().getStringExtra("uphone");
// 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);
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setSmallestDisplacement(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new
LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
Task<LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(
MapsActivity.this,
101);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
}
});
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//Check whether the network provider is enabled
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Get the Latitude
double latitude = location.getLatitude();
//Get the Longitude
double longitude = location.getLongitude();
//Instantiate the class, LatLng
LatLng latLng = new LatLng(latitude, longitude);
//Instantiate the class, GeoCoder
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getLocality()+",";
str += addressList.get(0).getCountryName()+",";
str += addressList.get(0).getPostalCode();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.0f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Get the Latitude
double latitude = location.getLatitude();
//Get the Longitude
double longitude = location.getLongitude();
//Instantiate the class, LatLng
LatLng latLng = new LatLng(latitude, longitude);
String name = new String(Prevelant.currentOnlineUser.getUsername());
//Instantiate the class, GeoCoder
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getLocality()+",";
str += addressList.get(0).getCountryName()+",";
str += addressList.get(0).getPostalCode();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng)
.zoom(17).build();
//Zoom in and animate the camera.
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case 101:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
Toast.makeText(MapsActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(MapsActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
Toast.makeText(this, "Please be patience until we find your current location...", Toast.LENGTH_SHORT).show();
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
// First check if myMarker is null
if (myMarker == null) {
// Marker was not set yet. Add marker:
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Accidnet Location")
.snippet("Put the marker to your accident location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MapsActivity.this, "Your location has been placed!", Toast.LENGTH_SHORT).show();
HashMap<String, Object> userMap = new HashMap<>();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Location").child(Prevelant.currentOnlineUser.getUsername());
myRef.child("name").setValue(userNAME);
myRef.child("phone").setValue(userPHONE);
myRef.child(Prevelant.currentOnlineUser.getUsername()).updateChildren(userMap);
finish();
Intent intent = new Intent(MapsActivity.this, LoginActivity.class);
startActivity(intent);
}
});
} else {
// Marker already exists, just update it's position
myMarker.setPosition(latLng);
LatLng myLatLng = new LatLng(myMarker.getPosition().latitude, myMarker.getPosition().longitude);
}
HashMap<String, Object> adminMap = new HashMap<>();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Location").child(Prevelant.currentOnlineUser.getUsername());
LatLng myLatLng = new LatLng(myMarker.getPosition().latitude, myMarker.getPosition().longitude);
myRef.child("latitude").setValue(myLatLng.latitude);
myRef.child("longitude").setValue(myLatLng.longitude);
myRef.child(Prevelant.currentOnlineUser.getUsername()).updateChildren(adminMap);
}
});
}
}
I have an Android Studio application that uses Google Maps, wherein I want to implement a "tag your location". What I want to happen is, the user could tag/input his location in google maps so other users could find his location.
For example, I am a stall owner and I want to input my location in a specific part of the market place so people could find directions to my stall.
Is there a way how to do that? And if yes, help me how to do it. Thanks in advance.
Here is my MapsActivity.java code:
package com.example.kliwa_000.sholocoo;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import Modules.DirectionFinder;
import Modules.DirectionFinderListener;
import Modules.Route;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, DirectionFinderListener{
private GoogleMap mMap;
private EditText destination, origin;
private Button btnFind;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
private List<Polyline> polylinePaths = new ArrayList<>();
private ProgressDialog progressDialog;
int PROXIMITY_RADIUS = 10000;
double latitude, longitude;
double end_latitude, end_longitude;
public static final String TAG = MapsActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Bundle bundle = getIntent().getExtras();
if (bundle != null){
if (bundle.get("some") != null){
Toast.makeText(getApplicationContext(), "" + bundle.get("some"), Toast.LENGTH_SHORT).show();
}
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
btnFind = (Button) findViewById(R.id.btnFind);
destination = (EditText) findViewById(R.id.destination);
origin = (EditText) findViewById(R.id.origin);
btnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendRequest();
}
});
}
private void sendRequest(){
String Sdestination = destination.getText().toString();
String Sorigin = origin.getText().toString();
try{
new DirectionFinder(this, Sorigin, Sdestination).execute();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
}
}
private void setUpMap(){
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
private void handleNewLocation(Location location){
Log.d(TAG, location.toString());
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
CameraUpdate zoom = CameraUpdateFactory.zoomTo(200);
mMap.moveCamera(zoom);
mMap.animateCamera(zoom);
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
LatLng userlocation = new LatLng(0, 0);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]
{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
}
return;
}
mMap.setMyLocationEnabled(true);
// mMap.addMarker(new MarkerOptions().position(userlocation).title("Current Location"));
/*LatLng seveneleven = new LatLng(16.4088, 120.5978 );
mMap.addMarker(new MarkerOptions().position(seveneleven).title("7/11 Gov. Pack").snippet("Carrots: Php 40/kilo"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(seveneleven));
LatLng ezzerm = new LatLng(16.4087, 120.5993 );
mMap.addMarker(new MarkerOptions().position(ezzerm).title("SM Baguio City").snippet("Carrots: Php 35/kilo"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(ezzerm));
LatLng burnham = new LatLng(16.4093, 120.5950 );
mMap.addMarker(new MarkerOptions().position(burnham).title("Burnham Park").snippet("Carrots: Php 45/kilo"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(burnham));
LatLng whitehouse = new LatLng(16.477949, 120.502748);*/
}
#Override
public void onDirectionFinderStart() {
progressDialog = ProgressDialog.show(this, "Please wait.",
"Finding direction..!", true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline:polylinePaths ) {
polyline.remove();
}
}
}
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
for (Route route : routes) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) findViewById(R.id.tvDistance)).setText(route.distance.text);
originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mMap.addPolyline(polylineOptions));
}
}
}
Honestly, my code is a little bit messy, but I'm trying to fix it.