I am developing an android app. My app needs to show a pin on Google Maps at the time user clicks on the ListView item but I don't want to put the Google Maps into my application - instead, I want to launch it using an Intent. Is this possible?
Following is my DisplayActivity.java file. I want to call Google maps app(if app not installed it should notify user) when user clicks on any item from nameAddressList which is assigned to ListView through adapter.
DisplayActivity:
enter code herepublic class DisplayActivity extends Activity {
ListView listView;
private String tag_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
listView = (ListView) findViewById(R.id.list);
Intent intent = getIntent();
if(intent!= null)
{
//int imageId = intent.getIntExtra("DashboardImage",R.drawable.apartments);
tag_name = intent.getStringExtra("DashItemName");
}
List<NameAddress> nameAddressList = null;
try {
XMLPullParserHandler parser = new XMLPullParserHandler(tag_name);
nameAddressList = parser.parse(getAssets().open("data.xml"));
ArrayAdapter<NameAddress> adapter =
new ArrayAdapter<NameAddress>(this,R.layout.list_item, nameAddressList);
listView.setAdapter(adapter);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display, menu);
return true;
}
}
To show route on Google Map, Just call an intent which passes current and destination latitude and longitude.After doing this, its Google Map's job to show location. You may also show street view.
In below code, there are three parameters : current_lat, current_longi, dest_address
final Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http:/a/maps.google.com/maps?"
+ "saddr="+ current_lat+","+current_longi + "&daddr="+dest_address ));
intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");
startActivity(intent);
If you have current address and destination address, then you can write like this :
Uri.parse("http://maps.google.com/maps?"
+ "saddr="+curr_address+ "&daddr="+dest_address ));
If you have current and destination latitude and longitude both then you can write like this :
Uri.parse("http://maps.google.com/maps?"
+ "saddr="+ current_lat+","+current_longi + "&daddr="+ destt_lat+","+dest_longi ));
When you call this intent, Google Map shows option whether to draw route by bus or by walk.
use below snippet and try..../
String uri = "geo:"+ latitude + "," + longitude;
startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri)));
Try this code,It was worked for me i think will you too.Here you have to put map package name.
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
startActivity(LaunchIntent);
You can use this to get latitude and longitude from Address
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
address = coder.getFromLocationName(strAddress,5);
if (address == null)
{
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
}
After getting Lat&Long you can pass this to google map with the help of following
Intent searchAddress = new Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+address));
startActivity(searchAddress);
Hope it will help you.
Related
I have an activity implementing OnMapReadyCallback to display some markers.
Before opening the map i provide a target city which i'd like to look at closer on the map basically by calling :
LatLng currentCity = new LatLng(cityLat,cityLng)
CameraUpdate location = CameraUpdateFactory.newLatLngZoom(currentCity,13);
googleMap.animateCamera(location);
The main problem here is that the zoom level is just an arbitrary number which works fine for some city and bad for others (Too zoomed in, Not enough zoomed in).
What i would like to achieve is to determine the zoom level dynamically depending on the city in the same way Google Maps does.
I know that the bigger the ViewPort of the city is, the smaller the zoom needs to be but i can't find a method to get the ViewPort for a given city and then changing the zoom level accordingly
EDIT : I was thinking about using a Geocoder to get a list of adress using the latitude and longitude of the city using
List<Address> addresses = mGeocoder.getFromLocation(Lat,Lon,maxLimit);
and then iterating over this list to find out the outermost adresses avaible for that city, in order to build a LatLngBounds to pass at setLatLngBoundsForCameraTarget() method.
The main problem with this approach is that, once again, the "maxLimit" is arbitrary and needs to be quite big for a big city, eventually returning a really big List
You can retrieve a view port for the city from the Geocoding API reverse geocoding response.
You should execute HTTP request to retrieve city view port from your activity. Once you receive the response you can construct the LatLngBounds instance and move camera accordingly.
Sample reverse geocoding request that gets city from coordinates is the following
https://maps.googleapis.com/maps/api/geocode/json?latlng=47.376887%2C8.541694&result_type=locality&key=YOUR_API_KEY
I wrote a small example for Map activity that receives lat and lng from the intent, executes the reverse geocoding HTTP request using the Volley library and moves camera to show the city view port.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private float lat;
private float lng;
private String name;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
this.lat = i.getFloatExtra("lat", 0);
this.lng = i.getFloatExtra("lng", 0);
this.name = i.getStringExtra("name");
mRequestQueue = Volley.newRequestQueue(this);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng pos = new LatLng(this.lat, this.lng);
mMap.addMarker(new MarkerOptions().position(pos).title(this.name));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pos));
this.fetchReverseGeocodeJson();
}
private void fetchReverseGeocodeJson() {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
"https://maps.googleapis.com/maps/api/geocode/json?latlng=" + this.lat + "%2C" + this.lng + "&result_type=locality&key=AIzaSyBrPt88vvoPDDn_imh-RzCXl5Ha2F2LYig",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String status = response.getString("status");
if (status.equals("OK")) {
JSONArray results = response.getJSONArray("results");
JSONObject item = results.getJSONObject(0);
JSONObject geom = item.getJSONObject("geometry");
JSONObject bounds = geom.getJSONObject("viewport");
JSONObject ne = bounds.getJSONObject("northeast");
JSONObject sw = bounds.getJSONObject("southwest");
LatLngBounds mapbounds = new LatLngBounds(new LatLng(sw.getDouble("lat"),sw.getDouble("lng")),
new LatLng(ne.getDouble("lat"), ne.getDouble("lng")));
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mapbounds, 0));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}
);
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
}
You can find a complete sample project at github:
https://github.com/xomena-so/so44735477
Hope this helps!
i have to show multiple location on the Native Google Map Application (MapView is not implemented in our application ).i have all the lat- long of all the geo Points . how can i pass the intent to show the multiple points on Native Google Map Application.
i know to show a point on Google map using the following Code.
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
please suggest how to do the needful changes.
Thanks :)
You can pass the names of the places that you want to show in the Map from the other Activity to the present Activity and then implement Markers to show them in the Map. For this you have to implement Google Map in the present Activity and I hope you have done that. :)
The below code shows multiple locations on a Google Map:
private void AddMarkers(GoogleMap googleMap)
{
try {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Geocoder geocoder = new Geocoder(context);
Origin_Map = extras.getString(MainActivity.ORIGIN_MAP);
Destination_Map = extras.getString(MainActivity.DESTINATION_MAP);
Addr_Origin = geocoder.getFromLocationName(Origin_Map, 1);
Addr_Dest = geocoder.getFromLocationName(Destination_Map, 1);
if (Addr_Origin.size() > 0) {
latitude_origin = Addr_Origin.get(0).getLatitude();
longitude_origin = Addr_Origin.get(0).getLongitude();
}
if (Addr_Dest.size() > 0) {
latitude_destination = Addr_Dest.get(0).getLatitude();
longitude_destination = Addr_Dest.get(0).getLongitude();
}
Marker m1 = googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude_origin, longitude_origin)).title(Origin_Map).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
Marker m2 = googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude_destination, longitude_destination)).title(Destination_Map).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
} catch (Exception e) {
e.printStackTrace();
}
}
And call this method once your map is ready!
#Override
public void onMapReady(GoogleMap googleMap)
{
AddMarkers(googleMap);
}
Hope this helps!!
Judging by this it is not possible. Also the question is a duplicate of this.
Now I'm using android map clicklistener to allow user to choose location from map. When the click the map the chosen location latitude and longitude are printed correctly in the toast, then I send this data to another fragment through bundle.
On android marshmallow devices it always transferred with null value, even it's working properly with all other versions.
I don't know what is the problem, so I'll be blessed for any help
Here is my code
try {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate Update = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(Update);
final Marker TP = map.addMarker(new MarkerOptions().position(latLng).title(""));
TP.setDraggable(true);
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
Toast.makeText(getActivity(), point.toString(), Toast.LENGTH_SHORT).show();
String latMap = String.valueOf(point.latitude);
String lngMap = String.valueOf(point.longitude);
((MainActivity)getActivity()).aqarLat = String.valueOf(point.latitude);;
((MainActivity)getActivity()).aqarLong = String.valueOf(point.longitude);
myBundle = new Bundle();
myBundle.putString("latMap" , latMap);
myBundle.putString("lngMap" , lngMap);
sharedPreferences.edit().putString("latMap", String.valueOf(point.latitude)).commit();
sharedPreferences.edit().putString("longMap", String.valueOf(point.longitude)).commit();
TP.setPosition(point);
}
});
} catch (Exception e) {
e.printStackTrace();
}
Thanks in advance
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
Is it possible to use it as library project for my application,i want to use Android Google Maps real app search-ability functionality. How can i do it,is it possible?
Thanks in advance..
EDIT:
I have shown Google Map in my app successfully, I want to include Google Map search functionality means that I can able to search any location in the world in auto suggested field and by selecting a particular location and move marker to that location. so how can I?
I tried this and this but not getting auto suggested text why I don't know..
I want like:
step1: show map with search box
step2: while entering text it should auto suggest.
step3: when click on particular name move map to that location
You can easily provide that kind of search functionality by using Places API and Geocode API (Both will help you according to your usecase).
Read the below Documentation for your assistance.
GeoCode API
Places API
I would recommend to use Places API for your need ( As per my observation on your usecase). But you could also use geocode, If you needed.
Many working reference and examples are there.
For startup, below are my reference :
PlacesAPI AutoComplete feature, Hotel Finder with Autocomplete
GeocodeAPI Simple GeoCoding
NOTE :
I have suggested javascript API. But not sure whether it will help you in Android environment (I dont know anything about android environment).
No single Api can help you have to use multiple google api's
Step1. Implement Google Place autocomplete Read this
Step2. You have to geocode means you have to convert address to latitude and longitude check this
Step3. Now You can plot these lat-long on the map.
This works for me.
I think you should take a look at the Google Maps API for Android at https://developers.google.com/maps/documentation/android/
The Google Search Appliance doesn't have any mapping or geo search features right now.
This is how I did it ---
Android Manifest file should contain the following lines:
<uses-library
android:name="com.google.android.maps"
android:required="true" >
</uses-library>
<!-- You must insert your own Google Maps for Android API v2 key in here. -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="<put your api key value here>" />
Location XML file should have the following apart from anything extra:
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Location java file should have something like this:
View mapView = null;
private GoogleMap mMap;
mMap = supportMapFragment.getMap();
mapView = (View) view.findViewById(R.id.map);
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
.findFragmentById(R.id.map);
if(mMap != null){
mMap.setMyLocationEnabled(true);
}
if(mMap != null)
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
new EditMap().execute("", String.valueOf(latLng.latitude), String.valueOf(latLng.longitude));
}
});
class EditMap extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
String address = args[0];
double latitude = Double.parseDouble(args[1]);
double longitude = Double.parseDouble(args[2]);
return editMap(address, latitude, longitude);
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
if(!result.equals(""))
ToastUtil.ToastShort(getActivity(), result);
else {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title(attvalue));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 11));
}
}
}
NOTE:
These are the minimal requirements for the setting of location as you choose from Map that fills the location in your text.
There is a background thread that runs as you long press the location in a map.
The listener defined for that is setOnMapLongClickListener as you see above.
The execution will place the marker to the exact location you chose to mark as set.
There will be a done button after you have chosen the location by a marker. This done button will confirm what you have chosen and will set that on a textfield for you.
The above code uses the method editMap to edit the map location.
The implementation is as done here:
private String editMap(String address, double latitude, double longitude ) {
String keyword = null;
try {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
if(!address.equals("")){
keyword = address;
java.util.List<android.location.Address> result = geocoder
.getFromLocationName(keyword, 1);
if (result.size() > 0) {
lat = (double) result.get(0).getLatitude();
lng = (double) result.get(0).getLongitude();
attvalue = address;
} else {
return "Record not found";
}
} else {
String sUrl = "http://google.com/maps/api/geocode/json?latlng="+latitude+","+longitude+"&sensor=true";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(sUrl);
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
try{
JSONObject jsonObject = new JSONObject(data);
JSONArray results = jsonObject.getJSONArray("results");
JSONObject addressObject = results.getJSONObject(0);
JSONArray addressComp = addressObject.getJSONArray("address_components");
String city = "", state = "";
for(int i=0; i < addressComp.length(); i++){
JSONArray types = addressComp.getJSONObject(i).getJSONArray("types");
if(city.equals("") && types.getString(0).equals("locality"))
city = addressComp.getJSONObject(i).getString("long_name");
if(state.equals("") && types.getString(0).equals("administrative_area_level_1"))
state = addressComp.getJSONObject(i).getString("long_name");
if(!city.equals("") && !state.equals(""))
break;
}
attvalue = city + ", " + state;
} catch (JSONException e1) {
e1.printStackTrace();
}
lat = latitude;
lng = longitude;
}else{
return "Location Not Found";
}
}
} catch (IOException io) {
return "Connection Error";
}
return "";
}
I hope this is enough to help you out.