google map: how to get address in android - android

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

Related

Set geofence radius to 200m, but Triggering location is at 50m distance from the geofence center. Why?

This is how I create the Geofence:
ArrayList geofences = new ArrayList<>();
geofences.add(new Geofence.Builder()
.setRequestId(geofenceRequestID)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(
location.getLatitude(), location.getLongitude(), radius)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build());
Where: geofenceRequestID = "1"; and the radius is: 200;
This is how I add the geofences:
mGeofencingClient.addGeofences(getGeofencingRequest(location, geofences), getGeofencePendingIntent(context)).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
isSettingGeofence = false;
Utils.makeNotification(context, "GEOFENCE ADDED: " + location.getLatitude() + ", " + location.getLongitude(), true);
PSLocationService.getInstance(context).setTrackingEnabled(false);
Utils.appendLog(context, "Geofence Transitions Service setGeofenceRequest Success adding geofences!" +
location.getLatitude() +
" , " + location.getLongitude(),
"I",
Constants.GEOFENCE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
isSettingGeofence = false;
Utils.appendLog(context, "Geofence Transitions Service setGeofenceRequest FAILURE adding geofences!" +
e.getMessage(),
"E",
Constants.GEOFENCE);
}
});
Now on handle intent. I do this:
Location triggering = geofencingEvent.getTriggeringLocation();
if(triggering != null) {
Utils.appendLog(PSGeofenceTransitionsIntentService.this, "GEOFENCE onHandleIntent got an EXIT transition: " + triggering.getLatitude() + ", " + triggering.getLongitude() + "/ " + triggering.getAccuracy(), "D", Constants.GEOFENCE);
}
I got to this case:
2017-10-17 14:38:32.615 30908:30908 [I] psngr.TRACKER.geofence Geofence Transitions Service setGeofenceRequest Success adding geofences! 52.37040665000001 , 4.9299061
2017-10-17 14:39:18.664 30908:8765 [D] psngr.TRACKER.geofence GEOFENCE onHandleIntent got an EXIT transition: 52.370363, 4.9306961/ 899.999
If you check the distance between them: https://www.google.nl/maps/dir/52.370363,+4.9306961/52.3704067,4.9299061/#52.370435,4.9300744,18.8z/data=!4m7!4m6!1m3!2m2!1d4.9306961!2d52.370363!1m0!3e3
Or with: http://www.gpsvisualizer.com/calculators it gives you a 54m distance.
Now I see that the accuracy of my triggering location is 899.999 but shouldn't the geofence mechanism take that in account? Is this a bug, do I need to raise it to google somehow? Or am I doing something wrong?

Is API Key Required for Direction Apis Android

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.

Dead code using android eclipse

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
}

Open url in another application or in browser [Titanium]

I am writing a functionality that needs to open a URL either in the another app [if installed in my phone] or else, in the browser.
To open the URL in browser, I can use Titanium.Platefor.openURL();
To open the app I am creating the intent.
var intent = Titanium.Android.createIntent({
packageName : appUrl,
action : Titanium.Android.ACTION_SEND,
data : url
});
intent.addCategory(Titanium.Android.CATEGORY_BROWSABLE);
Titanium.Android.currentActivity.startActivity(intent);
I have stuck in below things:
How to pass the url to other app to open - I tried passing url using url : 'http://someurl' and data: 'http://someurl' - but didn't help. I got the error: No Activity found to handle Intent
How to find out whether the app is install or not? If yes - ask for the application to open, if no - open the url in browser.
Can anyone help?
Thanks in advance!
You can identify app is install or not using URL schema with Titanium.Platefor.openURL(); method in android. (if app is not installed it will return false).
and for ios there is one method for identify Titanium.Platform.canOpenURL().
and also you can passed something value to application for example if you open google map application with source and destination lat long in ios then call like this
var strUrl = "http://maps.google.com/maps?saddr=" + Alloy.Globals.UserLocation.latitude + "," + Alloy.Globals.UserLocation.longitude + "&daddr=" + dLatitude + "," + dLongitude;
if (OS_IOS) {
strUrl = "comgooglemaps://?saddr=" + Alloy.Globals.UserLocation.latitude + "," + Alloy.Globals.UserLocation.longitude + "&daddr=" + dLatitude + "," + dLongitude + "&directionsmode=driving";
if (Titanium.Platform.canOpenURL(strUrl)) {
Ti.Platform.openURL(strUrl);
} else {
strUrl = "http://maps.google.com/maps?saddr=" + Alloy.Globals.UserLocation.latitude + "," + Alloy.Globals.UserLocation.longitude + "&daddr=" + dLatitude + "," + dLongitude;
Ti.Platform.openURL(strUrl);
}
} else {
var result = Ti.Platform.openURL(strUrl);
Ti.API.info('RESULT = ' + result);
}
one more example.. if you want opening whatsApp application with given message text.
var whatsappUrl = encodeURI('whatsapp://send?text=' + msgBody);
if (OS_IOS) {
if (Ti.Platform.canOpenURL(whatsappUrl)) {
Ti.Platform.openURL(whatsappUrl);
} else {
Ti.Platform.openURL("https://itunes.apple.com/ae/app/whatsapp-messenger/id310633997?mt=8");
}
} else {
var isSuccess = Ti.Platform.openURL(whatsappUrl);
if (!isSuccess) {
Ti.Platform.openURL("https://play.google.com/store/apps/details?id=com.whatsapp&hl=en");
}
}
Hop this is helps you.. :)
Thanks

Drawing a route on Google Maps API v2

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.

Categories

Resources