I am trying to have a simpler implementation of Google Map in my Android App. I am able to launch Google Map but I am unable to show multiple markers there. If I keep the latitude and longitude values and name of the places hardcoded then things work, but dynamically with variables and String values I am unable to show them.
I have also gone through this link suggested by many over here. But what I actually want is a simpler implementation of it.
Below is the code that I have used in my Main Activity:
public class Map_Activity_With_Fragment extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap googleMap;
String Origin, Destination, Start_Date, Num_Adult, Num_Infant, Origin_Map, Destination_Map;
Context context;
List<Address> Addr_Origin, Addr_Dest;
double latitude_origin, longitude_origin, latitude_destination, longitude_destination;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Origin = extras.getString(MainActivity.ORIGIN);
Destination = extras.getString(MainActivity.DESTINATION);
Start_Date = extras.getString(MainActivity.START_DATE);
Num_Adult = extras.getString(MainActivity.ADULT);
Num_Infant = extras.getString(MainActivity.INFANT);
Origin_Map = extras.getString(MainActivity.ORIGIN_MAP);
Destination_Map = extras.getString(MainActivity.DESTINATION_MAP);
context = Map_Activity_With_Fragment.this;
setTitle("Location Map");
setContentView(R.layout.activity_map__with__fragment);
try
{
initializeMap();
} catch (Exception 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.activity_map__with__fragment, menu);
return true;
}
#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;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onMapReady(GoogleMap googleMap)
{
AddMarkers(googleMap);
}
#Override
protected void onResume() {
super.onResume();
initializeMap();
}
private void initializeMap()
{
if (googleMap == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
private void AddMarkers(GoogleMap googleMap)
{
try {
Geocoder geocoder = new Geocoder(context);
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));
Marker m2 = googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude_destination, longitude_destination)).title(Destination_Map));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Please help me out!
Thanks in advance!
Ok, so I am going to update my own question.
I was testing these code changes on a device of API level 16, and hence the markers and polylines were not getting rendered correctly. Then I tested this same code on a device of API level 19, and it worked perfectly fine. I did not modify any part of code for this. Things are working now. :)
Related
I am trying to cluster markers that users input onMapLongClick but I can't seem to figure it out. All the tutorials/samples I've found show how to cluster for objects that are at a predetermined LatLng. This won't work for what I want to do because the point is not known until the user places a marker. For example, if users input twenty markers while using the app in a certain location at zoom level 7, then I want to be able to cluster them based on distance or a grid or however when they zoom to level 6. I am using Google Maps with Android Studio. Can anyone please help? I've been working for awhile on this...Here is the code I have so far. Thank you!
public class BasicMapDemoActivity extends AppCompatActivity implements
OnMapReadyCallback {
GoogleMap mMap;
private UiSettings mUiSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
if (item.getItemId() == R.id.menu_legal) {
startActivity(new Intent(this, LegalInfoActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
mUiSettings = mMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(true);
mUiSettings.setScrollGesturesEnabled(true);
mUiSettings.setZoomGesturesEnabled(true);
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
mMap.addMarker(new MarkerOptions()
.position(point)
.snippet("this is a snippet"));
}
});
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
}
});
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition position) {
float maxZoom = 7.0f;
if (position.zoom > maxZoom) {
mMap.animateCamera(CameraUpdateFactory.zoomTo(maxZoom));
}
}
});
}
}
The easiest way is to attach a ClusterManager to your map. It will automatically animate the markers from cluster at their position (or cluster them, when you zoom out).
The clustering is part of another project, called android-map-utils which can be found here:
https://github.com/googlemaps/android-maps-utils
They have a great demo application in the repository, I believe you will find the functionality you need there.
Example for adding items to ClusterManager, after you map has been initialised.
set up the cluster manager
mClusterManager = new ClusterManager<>(BrowseLocationsActivity.this, googleMap);
mClusterManager.setClusterOnlyVisibleArea(true);
mClusterManager.setAlgorithm(new VisibleNonHierarchicalDistanceBasedAlgorithm<MapMarkerItem>(metrics.widthPixels, metrics.heightPixels));
when you need to add a new item to your cluster, just call
mClusterManager.addItem(new MapMarkerItem(latitude, longitude));
mClusterManager.cluster();
Note thatMapMarkerItem is a custom class, that implementes ClusterItem from the library.
I'm developing an Android Application which is consists of a Navigation drawer and a Google Map. I have successfully developed my Navigation Drawer and connect my Map into it. The thing is I need my Map to Zoom to the current location.
Here is the code I used in MapsActivity.java.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Identify the current location of the device
mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving
Location currentLocation = getMyLocation(); // Calling the getMyLocation method
if(currentLocation!=null){
LatLng currentCoordinates = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 13.0f));
}
}
Here I implemented getMyLocation() method.
//Zoom to the current location
private Location getMyLocation() {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Get location from GPS if it's available
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Location wasn't found, check the next most accurate place for the current location
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
// Finds a provider that matches the criteria
String provider = lm.getBestProvider(criteria, true);
// Use the provider to get the last known location
myLocation = lm.getLastKnownLocation(provider);
}
return myLocation;
}
Here is How I gave MapsFragment in to NavigatioDrawerActivity.
fragment = new MapFragment();
When I run this alone (Insert intent filter to MapsActivity in Manifest) it works perfect. But, when I'm running the Nvigation Drawer as MainActivity this function is not working. Only the default Map is loading.
What should I do?
-edit-
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
My Maps.xml is like this.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
My whole MapsActivity.java
public class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Identify the current location of the device
mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving
initializaMap(rootView, savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void initializaMap(View rootView, Bundle savedInstanceState){
MapsInitializer.initialize(MapsActivity.this);
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(MapsActivity.this)) {
case ConnectionResult.SUCCESS:
mapView = (MapView) rootView.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
if (mapView != null) {
mMap = mapView.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings mUiSettings = mMap.getUiSettings();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9270786, 79.861243), 13));
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
#Override
public void onMyLocationChange(Location location) {
}
}
Here is my NavigationDrawer.java
public class NavigationDrawer extends ActionBarActivity {
private GoogleMap mMap;
String[] menutitles;
TypedArray menuIcons;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
private LinearLayout mLenear;
static ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_NavigationDrawer);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
mLenear = (LinearLayout)findViewById(R.id.left_drawer);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFA500")));
imageView=(ImageView)findViewById(R.id.profPic);
Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.ic_prof);
imageView.setImageBitmap(getCircleBitmap(bitmap));
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId( i, -1));
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.app_name,R.string.app_name)
{
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu(); }
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
initializaMap(savedInstanceState);
}
private void initializaMap(Bundle savedInstanceState){
MapsInitializer.initialize(Extract.this);
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(Extract.this)) {
case ConnectionResult.SUCCESS:
MapView mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
if (mapView != null) {
mMap = mapView.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings mUiSettings = mMap.getUiSettings();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9192, 79.8950), 13));
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
}
//Circle Image
public static Bitmap getCircleBitmap(Bitmap bitmap) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int radius = Math.min(h / 2, w / 2);
Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Bitmap.Config.ARGB_8888);
Paint p = new Paint();
p.setAntiAlias(true);
Canvas c = new Canvas(output);
c.drawARGB(0, 0, 0, 0);
p.setStyle(Paint.Style.FILL);
c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
c.drawBitmap(bitmap, 4, 4, p);
p.setXfermode(null);
p.setStyle(Paint.Style.STROKE);
p.setColor(Color.WHITE);
p.setStrokeWidth(3);
c.drawCircle((w / 2) + 2, (h / 2) + 2, radius, p);
return output;
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
Fragment fragment = null;
switch (position) {
case 0:
// fragment = new MapFragment();
//break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mLenear);
}
else {
// error in creating fragment
Log.e("Extract", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_extract, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default :
return super.onOptionsItemSelected(item);
}
}
/*** * Called when invalidateOptionsMenu() is triggered */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mLenear);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState(); }
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
try this ..
map.animateCamera(CameraUpdateFactory.newLatLngZoom((sydney), 13.0f));
you have not given by in float. so its not working.. try this..
try this
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 13));
In XML
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In JAVA Activity
private void initializaMap(Bundle savedInstanceState){
MapsInitializer.initialize(MainActivity.this);
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) {
case ConnectionResult.SUCCESS:
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
if (mapView != null) {
mMap = mapView.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings mUiSettings = mMap.getUiSettings();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 13));
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
}
call like this
initializaMap(savedInstanceState);
it will not work because the navigation drawer takes a fragment and you are initializing :
fragment = new MapFragment();
so it takes the MapFragment default layout .
you must to change the updateDisplay to takes an activity not a fragment . In another words change the navigation drawer to activities instead of fragments
I have an Android app for searching flights. I want to implement a Google Map where the Origin and the Destination will be shown in the map (with the help of some markers) to the user based on his/her inputs. But before I start anything, I need a help in the overall understanding.
Which API do I need? Google Maps API or Google Maps Direction API? I don't want to show any direction, only the places marked.
Is there any HTTP request for Google Maps API? Or how do I dynamically show the places in the map? I will only have the name of the places.
I would really appreciate if somebody can guide me through the initial steps of this implementation.
EDITED:
Below is the Main Activity that I am using:
public class Map_Activity_With_Fragment extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap googleMap;
String Origin, Destination, Start_Date, Num_Adult, Num_Infant, Origin_Map, Destination_Map;
Context context;
List<Address> Addr_Origin, Addr_Dest;
double latitude_origin, longitude_origin, latitude_destination, longitude_destination;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Origin = extras.getString(MainActivity.ORIGIN);
Destination = extras.getString(MainActivity.DESTINATION);
Start_Date = extras.getString(MainActivity.START_DATE);
Num_Adult = extras.getString(MainActivity.ADULT);
Num_Infant = extras.getString(MainActivity.INFANT);
Origin_Map = extras.getString(MainActivity.ORIGIN_MAP);
Destination_Map = extras.getString(MainActivity.DESTINATION_MAP);
context = Map_Activity_With_Fragment.this;
setTitle("Location Map");
setContentView(R.layout.activity_map__with__fragment);
try
{
initializeMap();
} catch (Exception 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.activity_map__with__fragment, menu);
return true;
}
#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;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onMapReady(GoogleMap googleMap)
{
AddMarkers(googleMap);
}
#Override
protected void onResume() {
super.onResume();
initializeMap();
}
private void initializeMap()
{
if (googleMap == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
private void AddMarkers(GoogleMap googleMap)
{
try {
Geocoder geocoder = new Geocoder(context);
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));
Marker m2 = googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude_destination, longitude_destination)).title(Destination_Map));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Google Maps API should be enough.
If you have location you can adds marker for each place https://developers.google.com/maps/documentation/android-api/marker
Get cooridnates:
How to get coordinates of an address in android
I have the following code and, when I press a menu button I would like to reposition the same marker and the camera but I do not have idea how to do it, I've read oficial documentation but I haven't found info. I'm using repositionMarker() method to do it, but Im not sure what to do. Thanks
public class Init extends AppCompatActivity implements OnMapReadyCallback
{
private MapFragment map;
static final LatLng PERTH = new LatLng(19.0436, -98.1981);
private CameraUpdate camaraloc, camaraloczoom;
private Marker markerloc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio);
map = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
if (map != null)
{
map.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap map)
{
map.setMyLocationEnabled(true);
camaraloc = CameraUpdateFactory.newLatLng(PERTH);
camaraloczoom = CameraUpdateFactory.zoomTo(8);
map.moveCamera(camaraloc);
map.animateCamera(camaraloczoom);
markerloc = map.addMarker(new MarkerOptions().position(PERTH)
.title("city").snippet("esp").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_inicio, menu);
return true;
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.action_settings:
Toast.makeText(this, "name marker: "+markerloc.getTitle(), Toast.LENGTH_SHORT).show();
reposicionMarker();
return true;
}
return super.onOptionsItemSelected(item);
}
public void repositionMarker()
{
camaraloc = CameraUpdateFactory.newLatLng(new LatLng(16.65, -91.8658));
camaraloczoom = CameraUpdateFactory.zoomTo(15);
if ( markerloc != null )
markerloc.remove();
markerloc.setPosition(new LatLng(16.65, -91.8658));
// here is where I dont know what to do
}
}
Calling setLocation on the Marker should work, for changing its location. What seems to be your problem is that you are actually removing the marker right before you set the new location.
below is my code which display map of all world i want when application start is show specific city not world map i follow this tutorial http://android-er.blogspot.com/2013/01/google-maps-android-api-v2-example-draw.html every thing work fine but i want when app start first time is display specific city map not all global map i dont want show globap map like this image http://1.bp.blogspot.com/-dwjqTWCdONg/UObUk1syAFI/AAAAAAAAGy8/S43YMKuXZRc/s1600/screen_MapsAPIv2_Polygon.png on app start i want specific city map like newyork for example.
public class MainActivity extends Activity
implements OnMapClickListener, OnMapLongClickListener, OnMarkerClickListener{
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Location myLocation;
TextView tvLocInfo;
boolean markerClicked;
PolygonOptions polygonOptions;
Polygon polygon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myMap.setOnMapClickListener(this);
myMap.setOnMapLongClickListener(this);
myMap.setOnMarkerClickListener(this);
markerClicked = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
int resultCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
#Override
public void onMapClick(LatLng point) {
tvLocInfo.setText(point.toString());
myMap.animateCamera(CameraUpdateFactory.newLatLng(point));
markerClicked = false;
}
#Override
public void onMapLongClick(LatLng point) {
tvLocInfo.setText("New marker added#" + point.toString());
myMap.addMarker(new
MarkerOptions().position(point).title(point.toString()));
markerClicked = false;
}
#Override
public boolean onMarkerClick(Marker marker) {
if(markerClicked){
if(polygon != null){
polygon.remove();
polygon = null;
}
polygonOptions.add(marker.getPosition());
polygonOptions.strokeColor(Color.RED);
polygonOptions.fillColor(Color.BLUE);
polygon = myMap.addPolygon(polygonOptions);
}else{
if(polygon != null){
polygon.remove();
polygon = null;
}
polygonOptions = new PolygonOptions().add(marker.getPosition());
markerClicked = true;
}
return true;
}
}
add this code to your onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
.
.
.
// define point to center on
LatLng origin = new LatLng(40.67, -73.94);
CameraUpdate panToOrigin = CameraUpdateFactory.newLatLng(origin);
myMap.moveCamera(panToOrigin);
// set zoom level with animation
myMap.animateCamera(CameraUpdateFactory.zoomTo(14), 400, null);
}
After the onClikListener are setted (into onCreate), put this code
LatLng NewYork= new LatLng(40.714623,-74.006605);
CameraPosition camPos = new CameraPosition.Builder().target(NewYork).zoom(14).build();
CameraUpdate cam = CameraUpdateFactory.newCameraPosition(camPos);
myMap.animateCamera(cam);
It will animate your map and move the camera to NY