open google maps through intent for specific location in android - android

I'm designing one application in which I want to show specific location on Map.
I'm passing String of address which is already placed on Google Map.
Following is my Intent code..
String url = "http://maps.google.com/maps?daddr="+address;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
But it gives me Google Map for getting direction. I know why that so, because I used daddr in url but I don't know what to use for specific location..Please tell me what to use there..

I have not tested this but you could try :
First method:
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
EDIT:
This might not work with Google maps 7,0
hence you could change the uri to :
Second option:
String geoUri = "http://maps.google.com/maps?q=loc:" + lat + "," + lng + " (" + mTitle + ")";
where mTitle is the name of the location.
Third option:
geo:0,0?q=my+street+address
Fourth option:
String map = "http://maps.google.co.in/maps?q=" + yourAddress;
Hope that works and helps :D..

Get Lat-Lng Using this web-service
http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false
Then Pass it to this code
String strUri = "http://maps.google.com/maps?q=loc:" + lat + "," + lng + " (" + "Label which you want" + ")";
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(strUri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
I hope it will help you
Thank you.

The latest version of map provides better solution. If you wish show an address on map use below code.
Uri mapUri = Uri.parse("geo:0,0?q=" + Uri.encode(address));
Intent mapIntent = new Intent(Intent.ACTION_VIEW, mapUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
If you want to display using latitude and longitude values, use below method.
Uri mapUri = Uri.parse("geo:0,0?q=lat,lng(label)");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, mapUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
Lat and lng being the latitude and longitude you wish to display, the label here is optional.

This will work like a charm. Make sure to check for existence for Google Maps, so this can work universally across all non Google devices also. It will open in a browser in such cases.
Also, remember, don't have www in the URL. Else this will not work.
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q=loc:" + latitude + "," + longitude));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Only if initiating from a Broadcast Receiver
String mapsPackageName = "com.google.android.apps.maps";
if (isPackageExisted(context, mapsPackageName)) {
i.setClassName(mapsPackageName, "com.google.android.maps.MapsActivity");
i.setPackage(mapsPackageName);
}
context.startActivity(i);
private static boolean isPackageExisted(Context context, String targetPackage){
PackageManager pm=context.getPackageManager();
try {
PackageInfo info=pm.getPackageInfo(targetPackage,PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return true;
}

As of 2020 you can also consider using Google Maps URLs, the API designed by Google in order to create universal cross-platform links. You can open Google maps on web, Android or iOS using the same URL string in form:
https://www.google.com/maps/search/?api=1&parameters
In case when you need show certain location you can use an URL like
https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324
The code snippet is
String url = "https://www.google.com/maps/search/?api=1&query="+address;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);

Uri gmmIntentUri = Uri.parse("geo:37.7749,-122.4194");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
Refer this documentation

try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" + src_lat+ "," + src_lng + "&daddr=" + des_lat + "," + des_lng));
startActivity(intent);
}catch (ActivityNotFoundException ane){
Toast.makeText(activity, "Please Install Google Maps ", Toast.LENGTH_LONG).show();
}catch (Exception ex){
ex.getMessage();
}
}
});

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + address));
startActivity(intent);

This helper method using uriBuilder for cleaner code and handle condition if there is no activity on device that can open map
public static boolean openMap(Context context, String address) {
Uri.Builder uriBuilder = new Uri.Builder()
.scheme("geo")
.path("0,0")
.appendQueryParameter("q", address);
Intent intent = new Intent(Intent.ACTION_VIEW, uriBuilder.build());
if (intent.resolveActivity(context.getPackageManager()) != null) {
context.startActivity(intent);
return true;
}
return false;
}

I find this solution in Google documentation so, it will work fine.
Double latitude = 37.7749,longitude = -122.4192;
String label = "Your location desired Aryan";
Uri gmmIntentUri =
Uri.parse("geo:0,0?q="+latitude+","+longitude+"("+label+")");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
context.startActivity(mapIntent);
If you have any doubt just comment it. I am not checking maps package because on every Android device we have maps. If you want you check it easily.

For the ones, who are looking for opening the "Maps" app for a particular location(by passing lat and long) and do not want that lat/long co-ordinates to be shown in Maps search bar after redirection(Opening Maps app). Instead wish to show some label or place name, you can refer to the code below,
private void openMapView(String latitude , String longitude , String locationName){
Uri gmmIntentUri = Uri.parse("geo:"+latitude+","+longitude+"?q="+locationName);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(context.getPackageManager()) != null) {
context.startActivity(mapIntent);
}
}
Note : "locationName" in the method above, represents the name you wish to display inside the Maps search bar.

To show location and disply show directions button inside google Maps use
this code snippet:
String geoUri = "http://maps.google.com/maps?q=loc:" + latitude + "," + longitude + " (" + locationName + ")";
Intent mapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(geoUri));
if (mapIntent.resolveActivity(context.getPackageManager()) != null) {
context.startActivity(mapIntent);

I thought I would chip in with the Kotlin code.
I created a helper function that takes latitude, longitude and context params to fire off the intent.
fun openGoogleMap(latitude: Double, longitude: Double, context: Context) { ... }
Inside the openGoogleMap() helper function create an intent passing in the action, data to act upon (lat/long) and package name for the Google Map application.
fun openGoogleMap(latitude: Double, longitude: Double, context: Context) {
// you need action, data and package name
val uri = Uri.parse("geo:$latitude,$longitude?z=15")
//create an intent
val mapIntent = Intent()
//add action & data
mapIntent.action = Intent.ACTION_VIEW
mapIntent.data = uri
//package name for google maps app
mapIntent.setPackage("com.google.android.apps.maps")
try {
context.startActivity(mapIntent)
} catch (e: ActivityNotFoundException) {
//if map app isn't resolved/installed catch error
e.printStackTrace()
}
}
The docs say that
To verify that an app is available to receive the intent, call
resolveActivity() on your Intent object. If the result is non-null,
there is at least one app that can handle the intent and it's safe to
call startActivity().
But I found that using resolveActivity() has issues when used with this code especially when you are outside the Activity's code.
mapIntent.resolveActivity(packageManager)?.let {
...
}
To get around this I used try-catch block to catch ActivityNotFoundException with startActivity().
mapIntent.setPackage("com.google.android.apps.maps")
try {
context.startActivity(mapIntent)
} catch (e: ActivityNotFoundException) {
//if map app isn't resolved/installed catch error
e.printStackTrace()
}
I tested the util function and it does work and is launching the GoogleMaps with Kotlin code.

If you have the name and address of the location available then you can launch the exact spot along with its images, details and navigation option using the following code :
fun loadLocation(ctx: Context, name: String, address: String) {
try {
val geoUri = "http://maps.google.com/maps?q=$name,$address"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(geoUri))
ctx.startActivity(intent)
}
catch (ex: Exception) {
ex.printStackTrace()
}
}

https://www.google.com/maps/dir//37.4219983,-122.084
String location = "https://www.google.com/maps/dir//" + latitude + "," + longitude;
try {
SmsManager sms = SmsManager.getDefault(); // using android SmsManager
sms.sendTextMessage(number, null, message + location, null, null); // adding number and text
Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Sms not send, please check phone number/network", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}

Related

How do I open google maps app on tapping an address?

I have an address param within my app say " 921 Beverly Hills, california, CA- 09001"
Upon tapping this I want google maps to open and show annotation for this exact address. How do I do that?
Any clue?
launch maps
There are great resources to get you going this is a sample. In a real app you would want to handle the intent with your own map activity; maybe add bounds and a camera to zoom in or whatever...
Location sf = new Location("");
sf.setLatitude(37.7749);
sf.setLongitude(-122.4194);
requestLocation("your address");
public void requestLocation(Location location) {
// Create a Uri from an intent string. Use the result to
// create an Intent.
Uri gmmIntentUri = Uri.parse("geo:" + location.getLatitude() + "," + location.getLongitude());
// Create an Intent from gmmIntentUri. Set the action to
// ACTION_VIEW
Intent mapIntent = new Intent(Intent.ACTION_VIEW,
gmmIntentUri);
// Make the Intent explicit by setting the Google Maps
// package
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(mapIntent, REQUEST_LOCATION);
}
}
public void requestLocation(String address) {
// Create a Uri from an intent string. Use the result to create
//an Intent.
Uri gmmIntentUri = Uri.parse("geo:" + address);
// Make the Intent explicit by setting the Google Maps
// package
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(mapIntent, REQUEST_LOCATION);
}
}
Here you can find an overview on how to use intents to start Google Maps with an Address:
https://developers.google.com/maps/documentation/urls/android-intents

How can I ask the user for Yandex Navi or Google Maps? How can I direct it?

I have two values in latitude and longitude. I have a key. This button must have two options to go to location information,Yandex Navi and Google Maps. When I click on the button, I want to know which one would like to open it. How can I do that?
You can use Intent.createChooser() like:
String url = "yandexmaps://maps.yandex.ru/?pt=" + latitude + "" + longitude + "&z=12&l=map";
Intent intentYandex = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intentYandex.setPackage("ru.yandex.yandexmaps");
String uriGoogle = "geo:" + latitude + "," + longitude;
Intent intentGoogle = new Intent(Intent.ACTION_VIEW, Uri.parse(uriGoogle));
intentGoogle.setPackage("com.google.android.apps.maps");
String title = "Select";
Intent chooserIntent = Intent.createChooser(intentGoogle, title);
Intent[] arr = new Intent[1];
arr[0] = intentYandex;
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arr);
startActivity(chooserIntent);
Andrii Omelchenko's answer always opens Google Maps for me. But after change google and Yandex order for chooserIntent, it is worked in my case:
val uriYandex = "yandexnavi://build_route_on_map?lat_to=${latitude}&lon_to=${longitude}"
val intentYandex = Intent(Intent.ACTION_VIEW, Uri.parse(uriYandex))
intentYandex.setPackage("ru.yandex.yandexnavi")
val uriGoogle = Uri.parse("google.navigation:q=${latitude},${longitude}&mode=w")
val intentGoogle = Intent(Intent.ACTION_VIEW, uriGoogle)
intentGoogle.setPackage("com.google.android.apps.maps")
val chooserIntent = Intent.createChooser(intentYandex, title)
val arr = arrayOfNulls<Intent>(1)
arr[0] = intentGoogle
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arr)
val activities = packageManager.queryIntentActivities(chooserIntent, 0)
if(activities.size>0){
startActivity(chooserIntent)
}else{
//do sth..
}
If it absolutely has to be either Google Maps or Yandex Navi, the easiest way would probably be to figure out which one the user wants to use (via a dialogue or similar), and then set that as the target of a Map Intent. For example, here's an intent from Google's Android documentation that targets Google Maps by app name:
// Creates an Intent that will load a map of San Francisco
Uri gmmIntentUri = Uri.parse("geo:37.7749,-122.4194");
Intent mapIntent = new Intent(Intent.ACTION_VIEW,
gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
This should also work with Navi by setting the package to "ru.yandex.yandexnavi".
Note, though, that a more standard way to do this would be with a Map Intent that doesn't specify the targeted app. That way, all you would have to provide is the coordinates, and then the user could use their app of choice:
public void showMap(Uri geoLocation) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}

Google Maps 7 started with geo intent is dropping a pin at the closest address to a coordinate instead of the exact location

In my app users can save the latitude and longitude of a particular location. I want them to able to launch other apps on their phone via a geo intent such as Google Maps so that they can easily get exact directions back to it. Here is the code I am using to generate the geo intent:
public static Intent getFindIntent(Context context) {
Intent intent = new Intent();
SharedPreferences prefs = Tools.getPrefs(context);
String latitude = prefs.getString(Const.LAT_KEY, "");
String longitude = prefs.getString(Const.LONG_KEY, "");
intent.setAction(Intent.ACTION_VIEW);
String uri = String.format(Locale.US, "geo:%s,%s?z=%d&q=%s,%s", latitude, longitude,
Const.ZOOM_LEVEL, latitude, longitude);
intent.setData(Uri.parse(uri));
return intent;
}
Obviously most people will use Google Maps since it's on everyone's phone. When I first released my application Google Maps would start and drop a pin at the exact coordinates specified in the q parameter of the geo uri that is set as data for the intent. With the release of Google Maps 7, maps seems to drop a pin at the closest address to the provided coordinates. This poses a problem to me since users should be able to navigate back to the saved position exactly, and not an address near it. The only place I have found this documented is here. The docs are from the official Android Developer site but they are very sparse. Are there alternatives to the geo intent to provide this functionality or is there something wrong with my code? I think Google Maps is breaking it's API contract since I am providing coordinates and not an address.
To drop the pin use this code:
try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("geo:" + AppointmentDetailLayout.docLatitude
+ "," + AppointmentDetailLayout.docLongitude
+ "?q=" + AppointmentDetailLayout.docLatitude
+ "," + AppointmentDetailLayout.docLongitude
+ "(" + label + ")"));
intent.setComponent(new ComponentName(
"com.google.android.apps.maps",
"com.google.android.maps.MapsActivity"));
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
try {
context.startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.google.android.apps.maps")));
} catch (android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=com.google.android.apps.maps")));
}
e.printStackTrace();
}
For directions use this :
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" + lat
+ "," + lng + "&daddr="
+ AppointmentDetailLayout.docLatitude + ","
+ AppointmentDetailLayout.docLongitude));
context.startActivity(intent);

google maps application from my application wid a label over the location

I can open google maps from my application and have a pointer over the location i am pointing to.
Instead i wanted to open google maps application from my application---- as is when user clicks on an address google maps application opens up with that particular point.
for that i used
startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:lat,lng?q=lat,lng")));
Here lat=34.456373 and lng=-45.464748
Google maps application is opening but that particular location is not coming up instead my present location is coming up.How to rectify that?
String geoCode = "geo:0,0?q=" + PLACE_LATITUDE + ","+ PLACE_LONGITUDE + "(" + PLACE_NAME + ")";
Intent sendLocationToMap = new Intent(Intent.ACTION_VIEW,
Uri.parse(geoCode));
startActivity(sendLocationToMap);
http://developer.android.com/guide/appendix/g-app-intents.html refer for more detail..
String uri = String.format("geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
see if this helps.
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
String showMap = String.valueOf(latitude) + ","
+ String.valueOf(longitude);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("geo:0,0?q=" + (showMap)));
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error in gps "+e, Toast.LENGTH_LONG).show();
}

How to open standard Google Map application from my application?

Once user presses button in my application, I would like to open standard Google Map application and to show particular location. How can I do it? (without using com.google.android.maps.MapView)
You should create an Intent object with a geo-URI:
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
If you want to specify an address, you should use another form of geo-URI: geo:0,0?q=address.
reference : https://developer.android.com/guide/components/intents-common.html#Maps
You can also simply use http://maps.google.com/maps as your URI
String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "&daddr=" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
or you can make sure that the Google Maps app only is used, this stops the intent filter (dialog) from appearing, by using
intent.setPackage("com.google.android.apps.maps");
like so:
String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "&daddr=" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
or you can add labels to the locations by adding a string inside parentheses after each set of coordinates like so:
String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "(" + "Home Sweet Home" + ")&daddr=" + destinationLatitude + "," + destinationLongitude + " (" + "Where the party is at" + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
To use the users current location as the starting point (unfortunately I haven't found a way to label the current location) then just drop off the saddr parameter as follows:
String uri = "http://maps.google.com/maps?daddr=" + destinationLatitude + "," + destinationLongitude + " (" + "Where the party is at" + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
For completeness, if the user doesn't have the maps app installed then it's going to be a good idea to catch the ActivityNotFoundException, as #TonyQ states, then we can start the activity again without the maps app restriction, we can be pretty sure that we will never get to the Toast at the end since an internet browser is a valid application to launch this url scheme too.
String uri = "http://maps.google.com/maps?daddr=" + 12f + "," + 2f + " (" + "Where the party is at" + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
try
{
startActivity(intent);
}
catch(ActivityNotFoundException ex)
{
try
{
Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(unrestrictedIntent);
}
catch(ActivityNotFoundException innerEx)
{
Toast.makeText(this, "Please install a maps application", Toast.LENGTH_LONG).show();
}
}
EDIT:
For directions, a navigation intent is now supported with google.navigation
Uri navigationIntentUri = Uri.parse("google.navigation:q=" + 12f + "," + 2f);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, navigationIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
Using String format will help but you must be care full with the locale. In germany float will be separates with in comma instead an point.
Using String.format("geo:%f,%f",5.1,2.1); on locale english the result will be "geo:5.1,2.1" but with locale german you will get "geo:5,1,2,1"
You should use the English locale to prevent this behavior.
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
To set an label to the geo point you can extend your geo uri by using:
!!! but be carefull with this the geo-uri is still under develoment
https://datatracker.ietf.org/doc/html/draft-mayrhofer-geo-uri-00
String uri = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f (%s)",
latitude, longitude, zoom, latitude, longitude, label);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
Check this page from google :
http://developer.android.com/guide/appendix/g-app-intents.html
You can use a URI of the form
geo:latitude,longitude
to open Google map viewer and point it to a location.
You can also use the code snippet below, with this manner the existence of google maps is checked before the intent is started.
Uri gmmIntentUri = Uri.parse(String.format(Locale.ENGLISH,"geo:%f,%f", latitude, longitude));
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
Reference: https://developers.google.com/maps/documentation/android-api/intents
To go to location WITH PIN on it, use:
String uri = "http://maps.google.com/maps?q=loc:" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
for without pin, use this in uri:
String uri = "geo:" + destinationLatitude + "," + destinationLongitude;
Sometimes if there's no any application associated with geo: protocal ,
you could use try-catch to get the ActivityNotFoundException to handle it.
It happens when you use some emulator like androVM which is not installed google map by default.
This is written in Kotlin, it will open the maps app if it's found and place the point and let you start the trip:
val gmmIntentUri = Uri.parse("http://maps.google.com/maps?daddr=" + adapter.getItemAt(position).latitud + "," + adapter.getItemAt(position).longitud)
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps")
if (mapIntent.resolveActivity(requireActivity().packageManager) != null) {
startActivity(mapIntent)
}
Replace requireActivity() with your Context.
I have a sample app where I prepare the intent and just pass the CITY_NAME in the intent to the maps marker activity which eventually calculates longitude and latitude by Geocoder using CITY_NAME.
Below is the code snippet of starting the maps marker activity and the complete MapsMarkerActivity.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.action_refresh) {
Log.d(APP_TAG, "onOptionsItemSelected Refresh selected");
new MainActivityFragment.FetchWeatherTask().execute(CITY, FORECAS_DAYS);
return true;
} else if (id == R.id.action_map) {
Log.d(APP_TAG, "onOptionsItemSelected Map selected");
Intent intent = new Intent(this, MapsMarkerActivity.class);
intent.putExtra("CITY_NAME", CITY);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public class MapsMarkerActivity extends AppCompatActivity
implements OnMapReadyCallback {
private String cityName = "";
private double longitude;
private double latitude;
static final int numberOptions = 10;
String [] optionArray = new String[numberOptions];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_map);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Test whether geocoder is present on platform
if(Geocoder.isPresent()){
cityName = getIntent().getStringExtra("CITY_NAME");
geocodeLocation(cityName);
} else {
String noGoGeo = "FAILURE: No Geocoder on this platform.";
Toast.makeText(this, noGoGeo, Toast.LENGTH_LONG).show();
return;
}
}
/**
* Manipulates the map when it's available.
* The API invokes this callback 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 receives a prompt to install
* Play services inside the SupportMapFragment. The API invokes this method after the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(latitude, longitude);
// If cityName is not available then use
// Default Location.
String markerDisplay = "Default Location";
if (cityName != null
&& cityName.length() > 0) {
markerDisplay = "Marker in " + cityName;
}
googleMap.addMarker(new MarkerOptions().position(sydney)
.title(markerDisplay));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
/**
* Method to geocode location passed as string (e.g., "Pentagon"), which
* places the corresponding latitude and longitude in the variables lat and lon.
*
* #param placeName
*/
private void geocodeLocation(String placeName){
// Following adapted from Conder and Darcey, pp.321 ff.
Geocoder gcoder = new Geocoder(this);
// Note that the Geocoder uses synchronous network access, so in a serious application
// it would be best to put it on a background thread to prevent blocking the main UI if network
// access is slow. Here we are just giving an example of how to use it so, for simplicity, we
// don't put it on a separate thread. See the class RouteMapper in this package for an example
// of making a network access on a background thread. Geocoding is implemented by a backend
// that is not part of the core Android framework, so we use the static method
// Geocoder.isPresent() to test for presence of the required backend on the given platform.
try{
List<Address> results = null;
if(Geocoder.isPresent()){
results = gcoder.getFromLocationName(placeName, numberOptions);
} else {
Log.i(MainActivity.APP_TAG, "No Geocoder found");
return;
}
Iterator<Address> locations = results.iterator();
String raw = "\nRaw String:\n";
String country;
int opCount = 0;
while(locations.hasNext()){
Address location = locations.next();
if(opCount == 0 && location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
country = location.getCountryName();
if(country == null) {
country = "";
} else {
country = ", " + country;
}
raw += location+"\n";
optionArray[opCount] = location.getAddressLine(0)+", "
+location.getAddressLine(1)+country+"\n";
opCount ++;
}
// Log the returned data
Log.d(MainActivity.APP_TAG, raw);
Log.d(MainActivity.APP_TAG, "\nOptions:\n");
for(int i=0; i<opCount; i++){
Log.i(MainActivity.APP_TAG, "("+(i+1)+") "+optionArray[i]);
}
Log.d(MainActivity.APP_TAG, "latitude=" + latitude + ";longitude=" + longitude);
} catch (Exception e){
Log.d(MainActivity.APP_TAG, "I/O Failure; do you have a network connection?",e);
}
}
}
Links expire so i have pasted complete code above but just in case if you would like to see complete code then its available at : https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753
Also, you can use external_app_launcher: https://pub.dev/packages/external_app_launcher
To know if is installed:
await LaunchApp.isAppInstalled(androidPackageName: 'com.google.android.maps.MapView', iosUrlScheme: 'comgooglemaps://');
To open:
await LaunchApp.openApp(
androidPackageName: 'com.google.android.maps.MapView',
iosUrlScheme: 'comgooglemaps://',
);
Uri gmmIntentUri = Uri.parse("google.streetview:cbll=46.414382,10.013988");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);

Categories

Resources