So I have looked around for examples of plotting routes on Google maps. However, my obstacle is that I have to go to url/route.coords in order to get the lat and lng for the route. When I go to that url manually it downloads a text file with all the route information. So if anyone could help me as to where to start that would be greatly appreciated. I already have the map showing along with a dot for your current location along with some other classes outlined. My end goal is to plot a different colored route for every drive, each drive has their specific URL.
Fragment for where I am showing my Google Maps:
public class ThirdFragment extends Fragment implements OnMapReadyCallback {
View myView;
private GoogleMap mMap;
MapFragment mapFrag;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.third_layout, container, false);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapFrag = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
//mapFrag.onResume();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 13);
mMap.animateCamera(yourLocation);
} else {
final AlertDialog alertDialogGPS = new AlertDialog.Builder(getActivity()).create();
alertDialogGPS.setTitle("Info");
alertDialogGPS.setMessage("Looks like you have not given GPS permissions. Please give GPS permissions and return back to the app.");
alertDialogGPS.setIcon(android.R.drawable.ic_dialog_alert);
alertDialogGPS.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intentSettings = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
startActivity(intentSettings);
alertDialogGPS.dismiss();
}
});
alertDialogGPS.show();
}
}
#Override
public void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mapFrag.getMapAsync(this);
}
else {
}
}
}
RouteCoord.java
public class RouteCoord {
private String lat, dist, lng, speed, index;
public String getLat() {
return lat;
}
public void setLat(String lat) {this.lat = lat;}
public String getLng(){return lng;}
public void setLng(String lng) {this.lng = lng;}
}
RouteAdapter.java
public class RouteAdapter extends ArrayAdapter<Map.Entry> {
private final Activity context;
// you may need to change List to something else (whatever is returned from drives.entrySet())
private final List<Map.Entry> drives;
public static String DriveURL;
public static String routeLat;
public static String routeLng;
SharedPreferences sharedPref;
// may also need to change List here (above comment)
public RouteAdapter(Activity context, List<Map.Entry> drives) {
super(context, R.layout.drive_url_list, drives);
this.context = context;
this.drives = drives;
sharedPref = context.getPreferences(Context.MODE_PRIVATE);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.third_layout, null, true);
Map.Entry drive = this.drives.get(position);
// position is the index of the drives.entrySet() array
int driveNum = position + 1;
// need to import your Route class
Route route = (Route) drive.getValue();
RouteCoord routeCoord = (RouteCoord) drive.getValue();
routeLat = routeCoord.getLat();
routeLng = routeCoord.getLng();
// need to import your URL class
DriveURL = route.getUrl();
return rowView;
}
}
You need to draw a Polyline on the Google Map using the coordinates of the route.
See below sample code:
/**
* To show map with this activity add ORIGIN, DESTINATION lat double arrays in
* intent.
*
* </br> For specifying origin, put latitude and longitude in an array of double
* with key = {#link #ORIGIN} in the intent </br >For specifying destination,
* put latitude and longitude in an array of double with key =
* {#link #DESTINATION} in the intent
*
* #author Shridutt.Kothari
*
*/
public class MapsActivity extends BaseActivity {
private static final String TAG = "MapsActivity";
/**
* String key for specifying array of long containing origin latitude and
* longitude .
*/
public static final String ORIGIN = "ORIGIN";
private double[] destinationLocation;
private GoogleMap map;
private PathUpdateReceiver pathUpdateReceiver;
private PolylineOptions lineOptions;
private Marker marker;
private MarkerOptions ambulanceMarkerOption;
private Polyline polyline;
private List<LatLng> points;
private static final int ZOOM_LEVEL = 15;
private static final int POLYLINE_WIDTH = 5;
private static final String AMBULANCE_MARKER_NAME = "Ambulance";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Intent launchIntent = getIntent();
// originLocation = new double[2];
// originLocation = launchIntent.getDoubleArrayExtra(ORIGIN);
// originLocation[0] = 28.628525;
// originLocation[1] = 77.22219016666666;
destinationLocation = new double[2];
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
if (null == map) {
try {
MapsInitializer.initialize(getApplicationContext());
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Google play services not available, can't show map!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
this.finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
if (null == pathUpdateReceiver) {
pathUpdateReceiver = new PathUpdateReceiver();
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AppConstants.VEHICLE_DATA_SAMPLE_ID);
registerReceiver(pathUpdateReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(pathUpdateReceiver);
}
/**
* PathUpdate
*
*
*/
private class PathUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (map != null
&& intent.getAction().equalsIgnoreCase(
AppConstants.VEHICLE_DATA_SAMPLE_ID)) {
map.getUiSettings().setZoomControlsEnabled(true);
map.getUiSettings().setTiltGesturesEnabled(true);
map.getUiSettings().setAllGesturesEnabled(true);
VehicleDataSample vehicleDataSample = ((GoldenHourTrackerApp) getApplication()).getVehicleDataSample();
destinationLocation[0] = vehicleDataSample.getLatitude();
destinationLocation[1] = vehicleDataSample.getLongitude();
Log.e(TAG, "received location update:"+destinationLocation[0]+", "+destinationLocation[1]);
LatLng newPoint = new LatLng(destinationLocation[0],
destinationLocation[1]);
if (null != destinationLocation) {
map.setTrafficEnabled(false);
map.setBuildingsEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng originlatlng = new LatLng(destinationLocation[0],
destinationLocation[1]);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
originlatlng, ZOOM_LEVEL));
-#SuppressWarnings("unused")
MarkerOptions traumaLoacationMarkerOption = new MarkerOptions()
.position(originlatlng)
.title(TRAUMA_LOCATION_MARKER_NAME)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
if (ambulanceMarkerOption == null) {
ambulanceMarkerOption = new MarkerOptions()
.position(originlatlng)
.title(AMBULANCE_MARKER_NAME)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// TODO: Currently Not adding
// TRAUMA_LOCATION_MARKER_NAME on Map
// map.addMarker(traumaLoacationMarkerOption);
marker = map.addMarker(ambulanceMarkerOption);
marker.showInfoWindow();
}
if (null == lineOptions) {
lineOptions = new PolylineOptions();
lineOptions.add(newPoint);
// A 5 width Polyline
lineOptions.width(POLYLINE_WIDTH);
lineOptions.color(context.getResources().getColor(
R.color.blue));
polyline = map.addPolyline(lineOptions);
}
marker.setPosition(newPoint);
marker.setVisible(true);
marker.showInfoWindow();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
newPoint, ZOOM_LEVEL));
points = polyline.getPoints();
points.add(newPoint);
polyline.setPoints(points);
}
}
}
}
}
Related
I am working on a project where I want to collect sensor data with coordinates and save them to a csv file.
The app was working perfectly before I started coding for getting the location.
I am using location manager but every time I install this app on my device the application just doesn't seem to work. I disappears after few seconds of installation.
Also note that I am saving the sensor data in every 20 milliseconds so should I collect the coordinate data in the same rate?
Sorry to put the whole code but I need help! Please let me know where should I make changes?
public class MainActivity extends AppCompatActivity implements SensorEventListener, LocationListener {
private SensorManager sensorManager;
private Sensor magnetic;
//Location
LocationManager locationManager;
Handler handler;
Location location;
double latitude;
double longitude;
// --o
private int counter = 1;
private boolean recording = false;
private boolean counterOn = false;
private float magValues[] = new float[3];
private Context context;
private static final int REQUESTCODE_STORAGE_PERMISSION = 1;
Collection<String[]> magneticData = new ArrayList<>();
private CsvWriter csvWriter = null;
public static DecimalFormat DECIMAL_FORMATTER;
TextView stateText;
EditText fileIDEdit;
//Location
TextView lat;
TextView lon;
//--o
TextView magText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Location
handler = new Handler();
lat = (TextView) findViewById(R.id.latitudeTextView);
lon = (TextView) findViewById(R.id.longitudeTextView);
//--o
findViewById(R.id.button).setOnClickListener(listenerStartButton);
findViewById(R.id.button2).setOnClickListener(listenerStopButton);
fileIDEdit = (EditText)findViewById(R.id.editText);
magText = (TextView) findViewById(R.id.textView3);
stateText = (TextView) findViewById(R.id.textView);
stateText.setText("Stand by");
context = this;
// Sensor
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
magnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setDecimalSeparator('.');
DECIMAL_FORMATTER = new DecimalFormat("#.000", symbols);
//Location
handler.postDelayed(runLocation, 1000);
}
public Runnable runLocation = new Runnable() {
#Override
public void run() {
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();
MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
}
};
private View.OnClickListener listenerStartButton = new View.OnClickListener() {
#Override
public void onClick(View v) {
recording = true;
stateText.setText("Recording started");
stateText.setTextColor(Color.parseColor("#FF0000"));
}
};
#Override
public void onSensorChanged(SensorEvent event) {
long timeInMillisec = (new Date()).getTime() + (event.timestamp - System.nanoTime()) / 1000000L;
// Some sensor operations
}
//magneticData.add(new String[]{String.valueOf(timeInMillisec), String.valueOf(magValues[0]), String.valueOf(magValues[1]), String.valueOf(magValues[2])});
#SuppressLint("SimpleDateFormat") SimpleDateFormat logLineStamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS", Locale.getDefault());
//logLineStamp.setTimeZone(TimeZone.getTimeZone("UTC"));
magneticData.add(new String[]{logLineStamp.format(new Date(timeInMillisec)), String.valueOf(x), String.valueOf(y), String.valueOf(z), String.valueOf(magnitude), String.valueOf(latitude), String.valueOf(longitude)});
counter++;
}
}
// Checks if the the storage permissions are given or not by the user
// It will request the use if not
private static boolean storagePermitted(Activity activity){
// Check read write permission
}
//Check Location
private void getLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
} else {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// Added Later
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location changed: "+latitude+" "+longitude, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
My lastLocation show in few devices and cruch my app
Here is my code:
...............................................................................................................................................................................................................................................................
public class MapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapView mMapView;
private View mView;
private MarkerOptions marker;
private Location location;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.activity_maps, container, false);
return mView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = view.findViewById(R.id.map);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
addMarker();
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
String lat1 = String.valueOf(lat);
String lng1 = String.valueOf(lng);
//Define list to get all latLng for the route
ArrayList<LatLng> path = new ArrayList<LatLng>();
//Execute Directions API request
GeoApiContext context = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
DirectionsApiRequest req = DirectionsApi.getDirections(context, lat1 + ", " + lng1, "31.742462, 34.985447");
try {
DirectionsResult res = req.await();
//Loop through legs and steps to get encoded polyLines of each step
if (res.routes != null && res.routes.length > 0) {
DirectionsRoute route = res.routes[0];
if (route.legs != null) {
for (int i = 0; i < route.legs.length; i++) {
DirectionsLeg leg = route.legs[i];
if (leg.steps != null) {
for (int j = 0; j < leg.steps.length; j++) {
DirectionsStep step = leg.steps[j];
if (step.steps != null && step.steps.length > 0) {
for (int k = 0; k < step.steps.length; k++) {
DirectionsStep step1 = step.steps[k];
EncodedPolyline points1 = step1.polyline;
if (points1 != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
for (com.google.maps.model.LatLng coord1 : coords1) {
path.add(new LatLng(coord1.lat, coord1.lng));
}
}
}
} else {
EncodedPolyline points = step.polyline;
if (points != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords = points.decodePath();
for (com.google.maps.model.LatLng coord : coords) {
path.add(new LatLng(coord.lat, coord.lng));
}
}
}
}
}
}
}
}
} catch (Exception ignored) {
}
//Draw the polyline
if (path.size() > 0) {
PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);
googleMap.addPolyline(opts);
}
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(31.742462, 34.985447), 10));
}
public void addMarker() {
marker = new MarkerOptions().position(new LatLng(31.742462, 34.985447)).title("בית הכנסת - נווה צדק").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mGoogleMap.addMarker(marker);
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(getContext(), "בית הכנסת - נווה צדק", Toast.LENGTH_SHORT).show();
return true;
}
});
}
I am trying to change the position of my location button in my Maps Android App from top to bottom. Seems like it is default in top. Please help me changing the position of it. I have taken the code from the google samples github. This is the new version of code which uses getMapAsync instead of getMap.
MapsActivity.java:
public class MapsActivity extends AppCompatActivity implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
/**
* Request code for location permission request.
*
* #see #onRequestPermissionsResult(int, String[], int[])
*/
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
/**
* Flag indicating whether a requested permission has been denied after returning in
* {#link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;
private GoogleMap mMap;
private PlaceAutocompleteFragment placeAutocompleteFragment;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
placeAutocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
// placeAutocompleteFragment.setFilter(new AutocompleteFilter.Builder().setCountry("ID").build());
placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
final LatLng latLngLoc = place.getLatLng();
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(latLngLoc).title(place.getName().toString()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngLoc));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onError(Status status) {
Toast.makeText(MapsActivity.this, "" + status.toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
enableMyLocation();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(point);
// changing the marker title
double lat = point.latitude;
double lng = point.longitude;
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = list.get(0);
String sublocality = address.getSubLocality();
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(sublocality);
// Clears the previously touched position
mMap.clear();
// Animating to the touched position
mMap.animateCamera(CameraUpdateFactory.newLatLng(point));
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
}
});
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
#Override
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
}
Guys, I have resolved it.
Add the following lines in your on create below SupportMapFragent.
View myLocationButton = mapFragment.getView().findViewById(0x2);
if (myLocationButton != null && myLocationButton.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
// location button is inside of RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myLocationButton.getLayoutParams();
// Align it to - parent BOTTOM|LEFT
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
// Update margins, set to 80dp
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80,
getResources().getDisplayMetrics());
params.setMargins(margin, margin, margin, margin);
myLocationButton.setLayoutParams(params);
}
I have a StringBuilder variable from which I want to get the final value and pass it to the another activity. And I want to display the final string value in edit text view.
I have tried to get the value using toString() method but I am unable to see the value in text view its blank.
String value=str.toString();
intent.putExtra("value",value);
startActivity(intent);
By this I have got the value and sending to 2nd activity.
Intent intent = this.getIntent();
String data = intent.getStringExtra("keyName");
edtxt_from.setText(data);
Using this I am getting the value in 2nd activity.
Whats going wrong??
Please help...
I am not getting the updated address in edit text view..
ChooseFromMapActivity
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
Intent intent;
double x, y;
StringBuilder str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(ChooseFromMapActivity.this,GoSend.class);
String value=str.toString();
intent.putExtra("value",value);
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSend
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
Location l=new Location();
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
//Bundle bundle = getIntent().getParcelableExtra("bundle");
// double fromPosition = bundle.getParcelable("from_position");
// edtxt_from.setText(fromPosition);
/* Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("latitude");
double longitude = extras.getDouble("Longitude");
edtxt_from.setText(String.valueOf(latitude));*/
Intent intent = this.getIntent();
String data = intent.getStringExtra("value");
edtxt_from.setText(data);
// Bundle bundle = intent.getExtras();
// Serializable value =bundle.getSerializable("value");
// edtxt_from.setText(String.valueOf(longitude));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}
Change
String data = intent.getStringExtra("keyName");
to
String data = intent.getStringExtra("value");
You were using the wrong key.
simply do :
Replace keyName by value
I try to send a Toast Message from a Thread to the UIThread when clicking a button.
However, every time I click the button the Toast does not appear.
I am using a Handler to do this.
This is the full code, in case I made a major mistake somewhere:
package google.map.activity;
//imports
public class GoogleMapActivity extends MapActivity {
int lat = 0;
int lng = 0;
Location location;
MapController mc;
GeoPoint p;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.googlemapactivity);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(false);
mapView.setSatellite(false);
mapController = mapView.getController();
mapController.setZoom(19);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5,
0, new GeoUpdateHandler());
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 5, 0, new GeoUpdateHandler());
// //////---Switch to
// Start/////////////////////////////////////////////////////////////////////////////
Button switchToMain = (Button) findViewById(R.id.switchtomain);
switchToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
// ////--Call a
// Cab/////////////////////////////////////////////////////////////////////////////////////
Button getCab = (Button) findViewById(R.id.GetCab); // create the Button
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
getCab.setOnClickListener(new View.OnClickListener() {
String bestProvider = locationManager.getBestProvider(criteria,
true);
Location locationTest = locationManager
.getLastKnownLocation(bestProvider); // get
// last
// known
// location fix from
// locationManager
public void getAddress() {
String msg = null;
Looper.prepare();
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager
.getLastKnownLocation(bestProvider);
Geocoder geocoder = new Geocoder(getBaseContext(), Locale
.getDefault());// create
// new
// GeoCoder
String result = null; // initialize result
try { // try to get Address list from location of bestProvider
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", "
+ address.getLocality();// set result
// to
// Streetname+Nr.
// and City
}
} catch (IOException e) {
msg = String.format("IOException!!");
} finally {
if (result != null) {
msg = String.format(result);
// Looper.loop();
} else
msg = String.format("Keine Position");
}
Message myMessage = new Message();
Bundle resBundle = new Bundle();
resBundle.putString("status", msg);
myMessage.obj = resBundle;
handler.sendMessage(myMessage);
}
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// Looper.myLooper();
// Looper.prepare();
getAddress(); // get the Address
Location locationTest = locationManager
.getLastKnownLocation(bestProvider);
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location2 = locationManager
.getLastKnownLocation(bestProvider);
int lat = (int) (location2.getLatitude() * 1E6); // get
// position
// for GeoPoint
int lng = (int) (location2.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng); // create
// GeoPoint
// for
// mapController
mapController.animateTo(point);
}
}).start();
// toast.show();
}
});
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), msg.toString(),
Toast.LENGTH_LONG);
}
};
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Thank you in advance!
Edit: Solved it by using this:
Handler toastHandler = new Handler();
Runnable toastRunnable = new Runnable() {public void run() {Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();}};
In the UIThread and this:
toastHandler.post(toastRunnable);
in the background thread.
Try this:
runOnUiThread(new Runnable()
{
public void run()
{
// Here you can make a Toast
}
});
Your toast needs to be done in the UI thread. Here's how to do that:
Note: ClassName.this is needed because this by itself will refer to your anonymous Runnable class.
runOnUiThread(new Runnable() {
#Override
public void run()
{
Toast.makeText(ClassName.this, R.string.something, Toast.LENGTH_LONG).show();
}
});