I am working on android application in which i am using a logic to find the direction of a person from coordinated. Everything is working fine but i got error at console: : "Dead Code". My code is given below, please explain me this thing.
private void direction() {
String userLocation = mLatitude + ","
+ mLongitude ;
if(userLocation!=null){
String distLocation = Constants.sMY_LOCATION.getLatitude() + ","
+ Constants.sMY_LOCATION.getLongitude();
String url = "https://maps.google.com/maps?f=d&saddr=" + userLocation
+ "&daddr=" + distLocation;
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}else{ // Getting Dead Code Yellow error here
finish();
Toast.makeText(getBaseContext(), "Please check your internet and try again!", Toast.LENGTH_SHORT).show();
}
}
It's because your else can't be reached
String userLocation = mLatitude + ","
+ mLongitude ;
if(userLocation!=null){
...
}else{
...
}
userLocation will never be null
The code in your else{} will never be reached because your string userLocation is initialized before the if statement, meaning it will never be null.
So the code in you else is effectively dead code.
You should check mLatitude and mLongitude for being null instead of whole String.
Example:
if (mLatitude != null && mLongitude != null) {
// String userLocation = ...
}
else {
// Your else code
}
Related
I want to get the GPS location of my device. I am using GeolocatorPlugin for Xamarin to get the Longitude and Latitude of my device. GPS is enabled on my device. I already added permission to my android manifest but I still get the error: "A geolocation error occured: Unauthorized" How can I fix this?
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync();
entLocation.Text = position.Longitude.ToString() + "," + position.Latitude.ToString();
}
catch (Exception ex)
{
//will catch any general exception and set message in a string
string msg = ex.Message;
await DisplayAlert("error", msg, "ok");
}
Put the code below inside your MainActivity.cs in your Android Project.
if(CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) != (int)Permission.Granted)
{
RequestPermissions(new string[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation }, 0);
}
I am using below code to get directions to a particular lat & lng using google api. But I have not used the api key. This app which I am making will soon be pushed to playstore. I just want to make sure what I am doing here is correct or will it cause any problem for me ?
Thanks in advance :)
if (pc.getLatitude() != null && pc.getLongitude() != null) {
double latitude = Double.parseDouble(pc.getLatitude());
double longitude = Double.parseDouble(pc.getLongitude());
String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=%f,%f (%s)", latitude, longitude, "Location");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
if (intent.resolveActivity(mContext.getPackageManager()) != null) {
Toast.makeText(mContext, R.string.toast_opening_google_maps, Toast.LENGTH_SHORT).show();
mContext.startActivity(intent);
} else {
Toast.makeText(mContext, R.string.toast_no_google_maps_warning, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(mContext, R.string.toast_no_ll_warning, Toast.LENGTH_LONG).show();
}
This is one more example of my api usage
String distanceUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?" +
"origins=" + mOriginLatLng.latitude + "," + mOriginLatLng.longitude +
"&destinations=" + destination.latitude + "," + destination.longitude +
"&mode=driving&language=en-EN&sensor=false";
According to the documentation, you don't need an API key to launch Google Maps using an Intent.
According to the documentation, you will need an API key to use the Distance Matrix API.
My question is this:
How can I share the location of a marker I place on the map via touch position(Google Maps V2) I have an info window and can see the lat long. I tried and tried to set a button on the map to send the location of the placed marker, and I just can't get it to work.
Please help me to solve this issue.
Here is the code logic I have used:
public void setSendButton(Button sendButton) {
sendButton = (Button) findViewById(R.layout.mymap);}
public void onClick(View v, String Location) {
Context context = getApplicationContext();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
if (googleMap.getMyLocation() != null) {
googleMap.getMyLocation();
}
Intent i = new Intent(android.content.Intent.ACTION_SEND);
Location = location.getLatitude() / 1E6 + "," + location.getLongitude() / 1E6;
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, settings.getString("message_subject", getString(R.string.share_location_subject)));
i.putExtra(Intent.EXTRA_TEXT, settings.getString("message_body", getString(R.string.share_location_body))
+ " http://maps.google.com/maps?q=loc:"
+ location);
try {
startActivity(Intent.createChooser(i, getString(R.string.share_title)));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(context, getString(R.string.no_way_to_share), Toast.LENGTH_LONG).show();
}
Observation and Answer was correct code was just static via misplaced logic. Turns out I did not need a button.
Lesson is just use the objects methods.
Thanks to all.
Mike
I have a set of points in a text file that I want to plot on a map (API v2) and draw a line through. Each of the points is a <Lat, Lng> and there are a total of 7253 such points in the text file. The code is as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_my_route_mock);
//Step 0. Get google map instance.
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if(map == null) {
Toast.makeText(getApplicationContext(), "Map is not available.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Map is available.", Toast.LENGTH_LONG).show();
}
//Step 0.a. Load a type of map.
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
//Step 0.b. Load your current location on the map.
map.setMyLocationEnabled(true);
if(po == null) {
po = new PolylineOptions();
}
//Toast.makeText(getApplicationContext(), "Location lat = " + loc.getLatitude() + " and longitude = " + loc.getLongitude(), Toast.LENGTH_LONG).show();
//Step 1. Set GPS to service provider.
locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mocLocProvider = locMgr.GPS_PROVIDER;
locMgr.addTestProvider(mocLocProvider, false, false, true, false, true, false, false, 0, 5);
locMgr.setTestProviderEnabled(mocLocProvider, true);
//locMgr.requestLocationUpdates(mocLocProvider, 0, 0, locLstnr);
//Step 2. Open file for reading from.
try {
is = getAssets().open("locationLogs.txt");
br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
line = br.readLine();
while(line != null) {
//while((line = br.readLine()) != null) {
//there is still a line in the file. parse for gps coordinates etc.
Location l = new Location(LocationManager.GPS_PROVIDER);
String[] details = line.split(","); //the array will contain date, time, lat, long, speed, altitude and accuracy.
l.setTime(System.currentTimeMillis());
l.setLatitude(Double.parseDouble(details[2]));
l.setLongitude(Double.parseDouble(details[3]));
l.setSpeed((float) Double.parseDouble(details[4]));
l.setAltitude(Double.parseDouble(details[5]));
l.setAccuracy((float) Double.parseDouble(details[6]));
//Toast.makeText(getApplicationContext(), l.getLatitude() + "," + l.getLongitude() + "," + l.getSpeed() + "," + l.getAltitude() + "," + l.getAccuracy() + "\n", Toast.LENGTH_SHORT).show();
locMgr.setTestProviderLocation(mocLocProvider, l);
po.add(new LatLng(l.getLatitude(), l.getLongitude()));
Log.v(this.toString(), "Number of po objects = " + po.getPoints().size());
//pl = map.addPolyline(po);
//Log.v(this.toString(), "number of polyline objects added = " + pl.getPoints().size());
line = br.readLine();
}
} catch(FileNotFoundException e) {
Log.v(this.toString(), "File not found.");
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v(this.toString(), "Cannot open file for reading from.");
}
}
After reading about 1300 points, the application collapses with an OutOfMemory exception. Though there are a whole host of threads dealing with memory leakage on Google Maps API v2, closer analysis with MAT reveals that the line: pl = map.addPolyline(po) is the culprit, hogging most of the memory. This turns out to be true, since after that line is commented out, the memory footprint of the above code is very small ~8MB for about 7k points read.
My question(s):
1. Is there anything wrong with the way Polylines object is being used to draw on the map? Once for every update?
2. If so, how can a line be drawn such that it does not take up too much memory? With Canvas and the like or drawing a line only after a certain number of points (say, 10 or so)?
3. Some developers who have used Maps API v2 in their application can maybe shed some light on the proper way to do this?
Call pl = map.addPolyline(po); after the loop to create one polyline and not to try to create 7000 polylines each one "one point longer" than the one before.
How to get the location or address from the google map when i am click on a particular address. IS it possible to use map overlay to collect the address from the map view.
Please Use below code for get address.
try {
Geocoder geo = new Geocoder(youractivityclassname.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
yourtextfieldname.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
yourtextfieldname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
//Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
}
And see below link for more information and complete example.
Using Google Maps in Android