Check if route contains a specific coordinates or not - android

I am currently developing an application in which i want to know if a route contains a certain set of lat long coordinates. Here is my code:
public class PathActivity extends FragmentActivity implements OnMapReadyCallback, RoutingListener {
private GoogleMap mMap;
FetchLocation fetchLocation;
LatLng start;
LatLng end;
ProgressDialog pd;
List<Polyline> polylines;
private static final int[] COLORS = new int[]{R.color.gradient_dark_pink};
FirebaseFirestore firestore;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_path);
//Receiving Object From Intent
Intent rcv = getIntent();
fetchLocation = (FetchLocation) rcv.getSerializableExtra("keyFetchLocationObject2");
pd = new ProgressDialog(this);
pd.setMessage("Please Wait...");
firestore = FirebaseFirestore.getInstance();
fetchAllTrafficLights();
polylines = new ArrayList<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
pd.show();
//Making a Path
start = new LatLng(fetchLocation.latitude, fetchLocation.longitude);
end = new LatLng(fetchLocation.destinationLatitude, fetchLocation.destinationLongitude);
Routing routing = new Routing.Builder()
.travelMode(Routing.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(false)
.waypoints(start, end)
.build();
routing.execute();
}
#Override
public void onRoutingFailure(RouteException e)
{
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
pd.dismiss();
}
#Override
public void onRoutingStart() {
}
#Override
public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex)
{
pd.dismiss();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(start, 16));
if(polylines.size()>0) {
for (Polyline poly : polylines) {
poly.remove();
}
}
polylines = new ArrayList<>();
//add route(s) to the map.
for (int i = 0; i <route.size(); i++)
{
//In case of more than 5 alternative routes
int colorIndex = i % COLORS.length;
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(getResources().getColor(COLORS[colorIndex]));
polyOptions.width(10 + i * 3);
polyOptions.addAll(route.get(i).getPoints());
Polyline polyline = mMap.addPolyline(polyOptions);
polylines.add(polyline);
Toast.makeText(getApplicationContext(),"Route "+ (i+1) +": distance - "+ route.get(i).getDistanceValue()+": duration - "+ route.get(i).getDurationValue(),Toast.LENGTH_SHORT).show();
// Start marker
MarkerOptions options = new MarkerOptions();
options.position(start);
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_start_blue));
mMap.addMarker(options);
// End marker
options = new MarkerOptions();
options.position(end);
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_end_green));
mMap.addMarker(options);
}
}
#Override
public void onRoutingCancelled() {
}
public void fetchAllTrafficLights()
{
pd.show();
firestore.collection("Controller").get().addOnCompleteListener(this, new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(Task<QuerySnapshot> task)
{
if(task.isSuccessful())
{
for(QueryDocumentSnapshot documentSnapshot : task.getResult())
{
Log.i("Hello", documentSnapshot.get("controllerLatitude").toString() + " " + documentSnapshot.get("controllerLongitude").toString());
pd.dismiss();
}
}
}
})
.addOnFailureListener(this, new OnFailureListener()
{
#Override
public void onFailure(Exception e)
{
Toast.makeText(PathActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
pd.dismiss();
}
});
}
}
I am using github library: https://github.com/jd-alexander/Google-Directions-Android to draw the route between two points.
The coordinated are already saved in the firestore database and are successfully fetched as shown in Log. Now I want to check if the lat long points fetched from database are in the path or not. Eg. If we move from point A to D, I want to check points B,C are present on the route or not. I also want to know does the google places api always give same route coordinates between two locations. Here is my object:
public class FetchLocation implements Serializable
{
public double latitude;
public double longitude;
public double destinationLatitude;
public double destinationLongitude;
public FetchLocation()
{
}
public FetchLocation(double latitude, double longitude, double destinationLatitude, double destinationLongitude) {
this.latitude = latitude;
this.longitude = longitude;
this.destinationLatitude = destinationLatitude;
this.destinationLongitude = destinationLongitude;
}
#Override
public String toString() {
return "FetchLocation{" +
"latitude=" + latitude +
", longitude=" + longitude +
", destinationLatitude=" + destinationLatitude +
", destinationLongitude=" + destinationLongitude +
'}';
}
}
The users source lat long are fetched in the previous activity using google place autocomplete- https://developers.google.com/places/android-sdk/autocomplete and are set in the object which is passed to this activity.
Anyone please help!!

Take a look at PolyUtil.isLocationOnPath(LatLng point, java.util.List<LatLng> polyline, boolean geodesic, double tolerance) method of Google Maps Android API Utility Library. You need to get polyline path from A to D and check each point from list (B and C) with isLocationOnPath() if it laying on A-D path. Something like that:
for (LatLng point : pointsBandCList) {
if (PolyUtil.isLocationOnPath(point, polylineFromAtoD.getPoints(), true, 100)) {
// "point" laying on A to D path
...
}
}
where 100 - is tolerance (in meters). You can adjust it for your task.

Related

How to draw route by selecting a markers with places autocomplete?

I want to draw route on map when I place the destination marker from the Places AutoComplete search bar. As soon as I select the Drop location from Auto Complete, I want the route. I have seen some examples of drawing path but can't find any via the Places Autocomplete. My map and Places Autocomplete are working properly. How do I do it?
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), "my_api_ke");
}
/*Map Initialisation*/
mv = findViewById(R.id.Gmapview);
mv.onCreate(savedInstanceState);
mv.getMapAsync(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = lm.getBestProvider(new Criteria(), false);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
checkLocationPermission();
enableMyLocationIfPermitted();
//Initialize AutoCompleteSupportFragment
//Pickup Search Bar
supportFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.pickup);
supportFragment1 = (AutocompleteSupportFragment) getSupportFragmentManager()
.findFragmentById(R.id.drop);
//Initialize the Fields to get Latitude and Langitude and name of the selected place.
supportFragment.setPlaceFields(Arrays.asList(Place.Field.LAT_LNG, Place.Field.NAME));
supportFragment1.setPlaceFields(Arrays.asList(Place.Field.LAT_LNG, Place.Field.NAME));
//Placing Pickup Marker
supportFragment.setOnPlaceSelectedListener(newPlaceSelectionListener(){
#Override
public void onPlaceSelected(#NonNull Place pickup) {
Log.i("PickUP", "Place: " + pickup.getName() + ", ");
String name = pickup.getName();
LatLng latLng = pickup.getLatLng();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(name);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
gm.addMarker(markerOptions);
gm.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
#Override
public void onError(#NonNull Status status) {
Log.i("pickup", "An error occurred: " + status);
}
});
//Placing Drop Marker
supportFragment1.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place drop) {
Log.i("Drop", "Place: " + drop.getName() + ", ");
String name = drop.getName();
LatLng latLng = drop.getLatLng();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
gm.addMarker(markerOptions);
gm.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
#Override
public void onError(#NonNull Status status) {
Log.i("drop", "An error occurred: " + status);
}
});
}
Supposing your LatLng objects are correct and you only need to draw routes, here what you should do
Create a Helper class called DirectionsJSONParser that will later decode your polyline and give you a list of latitude longitude objects.
Here is the link for that class DirectionsJSONParser
For RetrofitClient those are the imports make sure you add them
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
Add this to your build.gradle(app) file
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
Create a retrofit client
//this is a singleton of Retrofit
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if(retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
}
//return retrofit object
return retrofit;
}
}
Next create a google API interface
public interface IGoogleAPI {
#GET
Call<String> getPath(#Url String url);
}
Create a Common class
public class Common {
public static String baseURL = "https://maps.googleapis.com/";
public static IGoogleAPI getGoogleAPI() {
return RetrofitClient.getClient(baseURL).create(IGoogleAPI.class);
}
}
Last but not least , declare a variable in your activity
IGoogleAPI mService;
Initialize that variable in onCreate
mService = Common.getGoogleAPI();
Create a method to draw routes
private void getDirection() {
String requestAPI;
try {
requestAPI = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + pickupMarker.getLatitude() + "," + pickupMarker.getLongitude() +
"&destination=" + dropMarker.getLatitude() + "," + dropMarker.getLongitude() + "&" +
"key=" + getResources().getString(R.string.google_direction_apis);
mService.getPath(requestAPI)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
try {
new ParserTask().execute(response.body().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Don't forget
To add retrofit dependencies in your build.gradle
To change your API_KEY in the requestString.
It's a long code so if you have any problem tell me .
Call this function getDirection() after you get the drop location.
EDIT
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
ProgressDialog mDialog = new ProgressDialog(NavigationTracking.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.setMessage("Executing...");
mDialog.show();
}
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(strings[0]);
DirectionJsonParser parser = new DirectionJsonParser();
routes = parser.parse(jObject);
} catch (JSONException e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
mDialog.dismiss();
ArrayList points = null;
PolylineOptions polylineOptions = null;
Toast.makeText(NavigationTracking.this, "" + lists.size(), Toast.LENGTH_SHORT).show();
for (int i = 0; i < lists.size(); i++) {
points = new ArrayList();
polylineOptions = new PolylineOptions();
List<HashMap<String, String>> path = lists.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polylineOptions.addAll(points);
polylineOptions.width(10);
polylineOptions.color(Color.RED);
// the shortest line between two points
polylineOptions.geodesic(true);
}
if (polylineOptions != null) {
direction = mMap.addPolyline(polylineOptions);
}
}
}
Declare
private Polyline direction;
And add this test before calling getDirection()
if (direction != null)
direction.remove();
EDIT 2
Declare 2 LatLng variables before onCreate() like this :
LatLng pickupLoc;
LatLng dropLoc;
Then when you are picking places your code become like this
//Placing Pickup Marker
supportFragment.setOnPlaceSelectedListener(newPlaceSelectionListener(){
#Override
public void onPlaceSelected(#NonNull Place pickup) {
Log.i("PickUP", "Place: " + pickup.getName() + ", ");
String name = pickup.getName();
pickupLoc = pickup.getLatLng();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(pickupLoc );
markerOptions.title(name);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
gm.addMarker(markerOptions);
gm.moveCamera(CameraUpdateFactory.newLatLngZoom(pickupLoc, 11));
}
#Override
public void onError(#NonNull Status status) {
Log.i("pickup", "An error occurred: " + status);
}
});
//Placing Drop Marker
supportFragment1.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place drop) {
Log.i("Drop", "Place: " + drop.getName() + ", ");
String name = drop.getName();
dropLoc = drop.getLatLng();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(dropLoc );
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
gm.addMarker(markerOptions);
gm.moveCamera(CameraUpdateFactory.newLatLngZoom(dropLoc, 11));
//here you test if your locations aren't null call getDirection() like this
if (pickupLoc != null && dropLoc != null) {
if (direction != null)
direction.remove();
getDirection();
}
}
#Override
public void onError(#NonNull Status status) {
Log.i("drop", "An error occurred: " + status);
}
});
So the answer by #Amine is mostly correct but some slight changes are required which I am giving here :
private void getDirection() {
String requestAPI;
try {
requestAPI = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + pickuploc.latitude() + "," +
pickuploc.longitude() +
"&destination=" + droploc.latitude() + "," +
droploc.longitude() + "&" +
"key=" + getResources().getString(R.string.google_direction_apis);
/*If you get "PolylineOptions cannot be null" error and app crashes
while trying to draw polyline then try pasting your API
key in string directly like this "key=somekey". Though only for testing. */
mService.getPath(requestAPI)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, retrofit2.Response<String>
response) {
try {
new ParserTask().execute(response.body().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

ClusterManager OnClusterClickListener not called

Good afternoon every one, I manage my google maps v2 with cluster manager(I'm using this library android-maps-utils) and I want to get the diffrence when a marker clicked and when a cluster manager clicked, But methodes doesn't called, So what going wrong in my code, I spent 10 days in this small problem, So Please Help.
HERE IT IS MY WHOLE CODE:
public class BigClusteringDemoActivity extends BaseDemoActivity implements ClusterManager.OnClusterClickListener,ClusterManager.OnClusterItemClickListener {
private ClusterManager<MyItem> mClusterManager;
#Override
protected void startDemo() {
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.503186, -0.126446), 10));
mClusterManager = new ClusterManager<MyItem>(this, getMap());
getMap().setOnCameraChangeListener(mClusterManager);
try {
readItems();
} catch (JSONException e) {
Toast.makeText(this, "Problem reading list of markers.", Toast.LENGTH_LONG).show();
}
getMap().setOnMarkerClickListener(mClusterManager);
}
private void readItems() throws JSONException {
InputStream inputStream = getResources().openRawResource(R.raw.radar_search);
List<MyItem> items = new MyItemReader().read(inputStream);
for (int i = 0; i < 10; i++) {
double offset = i / 60d;
for (MyItem item : items) {
LatLng position = item.getPosition();
double lat = position.latitude + offset;
double lng = position.longitude + offset;
MyItem offsetItem = new MyItem(lat, lng);
mClusterManager.addItem(offsetItem);
}
}
}
#Override
public boolean onClusterClick(Cluster cluster) {
Log.d("cluster","clicked" + cluster.getItems());
return false;
}
#Override
public boolean onClusterItemClick(ClusterItem item) {
Log.d("cluster","clicked" + item.getPosition());
return false;
}
}
You have not connected your ClusterManager to the map with onClick
You have this one getMap().setOnCameraIdleListener(mClusterManager);
try adding these aswell
getMap().setOnMarkerClickListener(mClusterManager);
mClusterManager.setOnClusterClickListener(this);
mClusterManager.setOnClusterItemClickListener(this);`
This will use the implements for listeners you added.
I have managed to find sequence of ClusterManager initialization for click listeners finally work:
1) init maps
mMap = googleMap
2) init ClusterManager
mClusterManager = ClusterManager(requireContext(), mMap)
3) set Map OnMarkerClickListener
mMap.setOnMarkerClickListener(mClusterManager)
4) init ClusterManager
mClusterManager = ClusterManager(requireContext(), mMap)
5) set cluster click listeners
mClusterManager.setOnClusterItemClickListener {
println("CLUST ITEM CLICK")
return#setOnClusterItemClickListener false
}
mClusterManager.setOnClusterClickListener {
println("CLUST CLICK")
return#setOnClusterClickListener false
}
6) when you use your custom render init it now:
mClusterManager.renderer = CustomIconRenderer(requireContext(), mMap, mClusterManager)

Android Google Map Markers get latitude and longitude from address in Firebase

I'm trying to find out if it's possible to get latitude and longitude from address. I read that I can use Geocoder to convert address to Lat and Long.
However, I'm not sure how to implement this as I'm manually storing the address, lat and long of the location and retrieving it from firebase. I'm adding the markers on the map through the coords. But what I want is getting the coordinates from the address instead of the manually putting in the coords. Do I add the Geocoder function under the part where I retrieve the address? How do I do that?
This is the example I read :
How can I find the latitude and longitude from address?
LocationRemitActivity.java
public class LocationRemitActivity extends FragmentActivity implements OnMapReadyCallback {
public static final String EXTRA_NAME = "";
private static final String TAG = "tag";
private ClusterManager<StoreLatLng> mClusterManager;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remit_location);
ButterKnife.bind(this);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Marker Cluster
setUpClusterer();
mMap.getUiSettings().setIndoorLevelPickerEnabled(false);
}
private void setUpClusterer() {
// Position the map.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(1.304414, 103.834006), 17));
// Initialize the manager with the context and the map.
// (Activity extends context, so we can pass 'this' in the constructor.)
mClusterManager = new ClusterManager<>(this, mMap);
// Point the map's listeners at the listeners implemented by the cluster
// manager.
mMap.setOnCameraIdleListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
mMap.setOnInfoWindowClickListener(mClusterManager); //added
mMap.setInfoWindowAdapter(mClusterManager.getMarkerManager());
// Listener for Info-Window Click , Parse data to next activity.
mClusterManager.setOnClusterItemInfoWindowClickListener(new ClusterManager.OnClusterItemInfoWindowClickListener<StoreLatLng>() {
#Override
public void onClusterItemInfoWindowClick(StoreLatLng myItem) {
Intent intent = new Intent(LocationRemitActivity.this, SelectedStoreDetail.class);
intent.putExtra(EXTRA_NAME, myItem.getTitle());
intent.putExtra("snippet", myItem.getSnippet());
Bundle args = new Bundle();
args.putParcelable("latlng", myItem.getPosition());
intent.putExtra("bundle", args);
startActivity(intent);
}
});
// Setting Cluster On Click ~> Zoom in 1 level .
mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<StoreLatLng>() {
#Override
public boolean onClusterClick(final Cluster<StoreLatLng> cluster) {
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(cluster.getPosition(), (float) Math.floor(mMap.getCameraPosition().zoom + 1)), 300, null);
BottomSheetDialogFragment bottomSheetDialog = BottomSheetDialogFragment.getInstance();
bottomSheetDialog.show(getSupportFragmentManager(), "Custom Bottom Sheet");
return true;
}
});
// Add cluster items (markers) to the cluster manager.
addItems();
}
//
private void addItems() {
// Firebase Setup to Retrieve Data
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
if (postSnapshot.hasChild("Info")) {
// Get Data from Firebase (Name , Address , Lat , Lng)
String locationName = String.valueOf(postSnapshot.child("Info").child("Name").getValue());
String locationAddress = String.valueOf(postSnapshot.child("Info").child("Address").getValue());
double locationlat = (double) postSnapshot.child("Info").child("lat").getValue();
double locationlng = (double) postSnapshot.child("Info").child("lng").getValue();
if (locationName != null && locationAddress != null) {
// Create Marker inside MyItem + add markers to mClusterManager
StoreLatLng item = new StoreLatLng(locationlat, locationlng, locationName, locationAddress);
mClusterManager.addItem(item);
}
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});

Extract data from WAMP sql server database to Android App

My aim is to draw markers based on GPS coordinates received from the WAMP server. I am not being able to draw the markers, what should I improve in my code in order to do so?
The following is the code responsible of getting data from a database running on WAMP server and drawing the markers on the map:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private RequestQueue requestQueue;
private double lat;
private double lon;
private int flag;
private String showUrl = "http://<<LOCAL-IP-ADDRESS>/directory/showSensor.php";
#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);
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray sensorLocations = response.getJSONArray("Sensor Locations");
for (int i = 0; i < sensorLocations.length(); i++) {
JSONObject sensorLocation = sensorLocations.getJSONObject(i);
String latitude = sensorLocation.getString("lat");
String longitude = sensorLocation.getString("long");
String flg = sensorLocation.getString("flag");
if (flag == 1) {
lat = Double.parseDouble(latitude);
lon = Double.parseDouble(longitude);
flag = 0;
}
}
;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
/**
* 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;
// Add a marker in Sydney and move the camera
LatLng sensor = new LatLng(lat, lon);
mMap.addMarker(new MarkerOptions().position(sensor).title(lat + "," + lon));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sensor));
}
}
It seems that the onMapReady method gets called before you receive a response from your server. Move the code to request data from your server to the onMapReady method:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray sensorLocations = response.getJSONArray("Sensor Locations");
for (int i = 0; i < sensorLocations.length(); i++) {
JSONObject sensorLocation = sensorLocations.getJSONObject(i);
String latitude = sensorLocation.getString("lat");
String longitude= sensorLocation.getString("long");
String flg = sensorLocation.getString("flag");
if(flag ==1 ) {
lat = Double.parseDouble(latitude);
lon = Double.parseDouble(longitude);
flag=0;
LatLng sensor = new LatLng(lat, lon);
mMap.addMarker(new MarkerOptions().position(sensor).title(lat+ " " + lon));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sensor));
}
}
;
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}

Android get the current location as start point in Google Maps Android API V2

I am trying to create route from current location to the direction, now i can use fixed latitude and longitude, but how to use my current location.
this is my file:
public class DirectionActivity3 extends FragmentActivity {
TextView textProgress;
Button buttonAnimate, buttonRequest;
double mLatitude=0;
double mLongitude=0;
GoogleMap mMap;
GoogleDirection gd;
Document mDoc;
LatLng start = new LatLng(mLatitude,mLongitude);
LatLng end = new LatLng(3.158847, 101.713837);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_direction_1);
mMap = ((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(start, 15));
gd = new GoogleDirection(this);
gd.setOnDirectionResponseListener(new OnDirectionResponseListener() {
public void onResponse(String status, Document doc, GoogleDirection gd) {
mDoc = doc;
mMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
buttonAnimate.setVisibility(View.VISIBLE);
}
});
gd.setOnAnimateListener(new OnAnimateListener() {
public void onStart() {
textProgress.setVisibility(View.VISIBLE);
}
public void onProgress(int progress, int total) {
textProgress.setText((int)((float)progress / total * 100) + "% / 100%");
}
public void onFinish() {
buttonAnimate.setVisibility(View.VISIBLE);
textProgress.setVisibility(View.GONE);
}
});
textProgress = (TextView)findViewById(R.id.textProgress);
textProgress.setVisibility(View.GONE);
buttonRequest = (Button)findViewById(R.id.buttonRequest);
buttonRequest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.GONE);
gd.setLogging(true);
gd.request(start, end, GoogleDirection.MODE_DRIVING);
}
});
buttonAnimate = (Button)findViewById(R.id.buttonAnimate);
buttonAnimate.setVisibility(View.GONE);
buttonAnimate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.GONE);
gd.animateDirection(mMap, gd.getDirection(mDoc), GoogleDirection.SPEED_VERY_SLOW
, true, false, true, true
, new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.car))
, true, false, null);
}
});
}
public void onPause() {
super.onPause();
gd.cancelAnimated();
}
}
And one more question, I want to use Google Place API to get somewhere's latitude and longitude as direction, and use my current location to create route.
This is my direction file:
public class PlaceActivity3 extends Activity {
final String ApiKey = "AIzaSyDQ6mA6vUHD3cMNqDoblES6q3dFHzNLqs4";
double latitude = 3.158847;
double longitude = 101.713837;
int radius = 1000;
String type = PlaceType.FOOD;
String language = "en";
String keyword = "japan restaurant food";
TextView textStatus;
ListView listView;
GooglePlaceSearch gp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_1);
textStatus = (TextView)findViewById(R.id.textStatus);
listView = (ListView)findViewById(R.id.listView);
gp = new GooglePlaceSearch(ApiKey);
gp.setOnPlaceResponseListener(new OnPlaceResponseListener() {
public void onResponse(String status, ArrayList<ContentValues> arr_data,
Document doc) {
textStatus.setText("Status : " + status);
if(status.equals(GooglePlaceSearch.STATUS_OK)) {
ArrayList<String> array = new ArrayList<String>();
final ArrayList<String> array_photo = new ArrayList<String>();
for(int i = 0 ; i < arr_data.size() ; i++) {
array.add("Name : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_NAME) + "\n"
+ "Address : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_ADDRESS) + "\n"
+ "Latitude : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_LATITUDE) + "\n"
+ "Longitude : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_LONGITUDE) + "\n"
+ "Phone Number : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_PHONENUMBER));
array_photo.add(arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_PHOTO));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PlaceActivity3.this
, R.layout.listview_text, array);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Dialog dialog = new Dialog(PlaceActivity3.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_photo);
dialog.setCancelable(true);
final ImageView imgPhoto = (ImageView)dialog.findViewById(R.id.imgPhoto);
dialog.show();
gp.getPhotoBitmapByWidth(array_photo.get(arg2), 600, ""
, new OnBitmapResponseListener() {
public void onResponse(Bitmap bm, String tag) {
imgPhoto.setImageBitmap(bm);
}
});
}
});
}
}
});
gp.getNearby(latitude, longitude, radius, type, language, keyword);
}
}
For the current location, you can use the LocationServices's getLastLocation() function:
which should look something like this:
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}
https://developer.android.com/training/location/retrieve-current.html#last-known
OR, you can use the Google Maps Location Data API:
https://developers.google.com/maps/documentation/android/location
For your destination's lat/lng, you should use the The Google Geocoding API:
https://developers.google.com/maps/documentation/geocoding/#GeocodingResponses

Categories

Resources