Mylocation button dont show up - android

I'm using Android Studio and using a map activity my map shows up fine, but the Mylocation button in the activity doesn't show. My google play services are installed. What am I doing wrong?
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}

You have to add this line in your code, replace your old code for this one :
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
if (mMap != null) {
//edit this
}
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);//here's the button
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
Also you have to add this in your manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
If my answer didn't help you, you can follow this tutorial and do what it says step by step :)

Check this for your setUpMapIfNeeded() method:
Android Google Maps setMyLocationEnabled(true)

To enable the location on your Google Maps if the Google Maps is visible on the activity/fragment.
Create an instance of the Google Map:
GoogleMap googleMap;
Inside your main activity that implements LocationListener
Add this line in your code to see the My Location Button:
googleMap.setMyLocationEnabled(true);
Don't forget to add the permissions in the manifest file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
For more details please refer to this tutorial.

Related

access location with google maps

I want to access my location using google maps and I don't know why it doesn't work.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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 sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
that is what appears when I rule the emulator:
Now I try to learn sth about maps, but in final I want to press on a button and to apear in google maps the location of a restaurant or sth else. How can I do this?
This is the Complete Code for accessing device location (not including the maps key part which i think you have already done)
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener
{
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
public Location mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
public void onConnected( Bundle bundle) {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
}
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation != null && mMap != null) {
LatLng tun = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(tun).title("Marker in Sydney"));
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
you have to write this code in the manifest.xml as well
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
this will allow app to be able to use device's location
The only thing that remains is that you MUST do GRANT the access of the Location by going to the settings of the app in the permissions menu Allow App for GPS location in other case it will not show the location
'com.google.android.gms:play-services:11.0.2'
you have to compile play services in order to access LocationListener
Did you add the acces location permissions in the manifest

Based On Co-ordinates show location on MAP in android

I have made an app which gives you current latitude and longitude using GPS service.
Now i plan to show location on MAP based on this co-ordinates
I want to create 2 activities. 1st already created in which i am showing latitude and longitude in TextView. in 2nd activity i want to display map in which location will be displayed. to go from one activity to another i will use a button in 1st activity.
here is my code (Not Full)
protected LocationManager locMan;
protected LocationListener locLis;
protected Context contex;
TextView txtview;
String lat,provider;
protected String latitude,longtitude;
protected boolean gps_enable,network_enable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F44336")));
txtview = (TextView)findViewById(R.id.locView);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location loc){
txtview = (TextView)findViewById(R.id.locView);
txtview.setText("Latitude = "+loc.getLatitude()+", Longitude = "+ loc.getLongitude());
}
Note :- I have refer javapapers website for my current app
Regards
Create Map Activity and pass the location via bundle or save it in sharedpreference
public class MapActivity extends ActionBarActivity{
private GoogleMap googleMap;
FragmentManager fm;
private Location mLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
// get location from bundle or sharedprefs
// mLocation = ...
try {
if (googleMap == null) {
googleMap = ((SupportMapFragment) fm.findFragmentById(R.id.map)).getMap();
googleMap.getUiSettings().setZoomGesturesEnabled(true);
}
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
MarkerOptions TP = new MarkerOptions().title("title").position(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_marker));
googleMap.addMarker(TP);
}}
xml layout for this activity is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
You need to use MapView and MyLocationOverLay to the map, as Android will handle displaying the user's location for you.
map=(MapView)findViewById(R.id.whatever_your_mapview_id_is);
map.getOverlays().add(new MyLocationOverlay(this, map));
Refer : display google maps using coordinates obtained using gps
You can pass the location to the Maps Activity using a LatLng Object since it's parcelable, see this answer.
Then, you could create a Marker in your MapsActivity, and use the CameraPosition class to move the map view to the specified location.
First, make sure that you have double values with the current location in your existing Activity:
//instance variables:
double lat;
double lon;
Set lat/lon in your onLocationChanged() callback:
#Override
public void onLocationChanged(Location loc){
lat = loc.getLatitude(); //added
lon = loc.getLongitude(); //added
txtview = (TextView)findViewById(R.id.locView);
txtview.setText("Latitude = "+loc.getLatitude()+", Longitude = "+ loc.getLongitude());
}
Create a Button in your layout in your existing Activity, and in the click listener you would create a LatLng object and send it in the Intent to the Maps Activity:
Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LatLng fromPostion = new LatLng(lat, lon );
Bundle args = new Bundle();
args.putParcelable("location", fromPostion);
Intent i = new Intent(this, MapsActivity.class);
i.putExtras(args);
startActivity(i);
}
});
Then, in your Maps Activity, you would get the LatLng object in onCreate() from the Bundle:
LatLng latlng; //Create as instance variable
In onCreate():
Bundle b = getIntent().getExtras();
if (b != null){
latlng = (LatLng) b.getParcelable("location");
}
Then, add the Marker at that location and set the camera position and zoom:
private void setUpMap() {
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);
MarkerOptions marker = new MarkerOptions().position(latlng).title("My Location");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
Marker m = mMap.addMarker(marker);
//move camera position and zoom to specified location
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latlng).zoom(8).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
Your full Maps Activity might look something like this:
public class MapsActivity extends ActionBarActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, OnMapReadyCallback {
private GoogleMap mMap;
LatLng latlng;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LocationManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Bundle b = getIntent().getExtras();
if (b != null){
latlng = b.getParcelable("location");
}
manager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
setUpMapIfNeeded();
buildGoogleApiClient();
mGoogleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle("Location is disabled")
.setMessage("Please enable your location")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 100);
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
Log.v("Connection Status", String.valueOf(mGoogleApiClient.isConnected()));
mGoogleApiClient.connect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 100) {
Toast.makeText(this, "location enabled", Toast.LENGTH_LONG).show();
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Toast.makeText(this, "location enabled", Toast.LENGTH_LONG).show();
//At least one provider enabled, connect GoogleApiClient
mGoogleApiClient.connect();
}
}
}
#Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this,"onConnected", Toast.LENGTH_SHORT).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
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 setUpMap() {
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);
MarkerOptions marker = new MarkerOptions().position(latlng).title("My Location");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
Marker m = mMap.addMarker(marker);
//move camera position and zoom to specified location
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latlng).zoom(8).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
Log.d("locationtesting", "lat: " + location.getLatitude() + " lon: " + location.getLongitude());
}
}
layout xml for MapsActivity:
<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" />
Note that you will also need to enable Google Maps in the Google Developer Console, and include Google Play Services in your build.gradle file (update version with the version that you are using):
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.google.android.gms:play-services:7.3.0'
}
The last thing is to set up your AndroidManifest.xml for the Google Maps API v2:
permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
meta-data tags, make sure they are inside the application tag:
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your-API-Key" />

Starting a map with current location

public class MainActivity extends FragmentActivity{
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
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 setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
//mMap.setMyLocationEnabled(true);
}
}
This is my Activity.
I want to start my app with my current location. I looked for some codes but none have the answer that I want. Can someone tell me what I should add?
Did you try:
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
Please use Android's LocationManager to get Lat/Lng with respect to your current services. Please refer to this answer that explains the usage of LocationManager.
After getting a Location object from the LocationManager, use the lat/lng to position the map like this.

How can I add a Marker in google map?

I want to add one Marker in Google map. I successfully loaded map in my app but when I tried to add a Marker, the app got crashed. I don't know why. Please some one help me!
My code:
public class BasicMapActivity extends FragmentActivity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
setUpMap();
}
#Override
protected void onResume() {
super.onResume();
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
Layout.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/map2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
Create a method setUpMapIfNeeded() and called on onResume() and onCreate()
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();
}
}
}
First you need to obtain the map from the SupportMapFragment and then you add Marker into map using
mMap.addMarker(new MarkerOptions().position(new LatLng(Your_lat, Your_long)).title("Marker"));
Try This
private void setUpMap() {
Marker pos_Marker = googleMap.addMarker(new MarkerOptions().position(starting).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_laumcher)).title("Starting Location").draggable(false));
pos_Marker.showInfoWindow();
}

Not able to implement Google Map V2

I'm trying to implement Google Map. But i'm getting Inflating error. Can anyone please provide a sample code to implement google map.
Thank you
Here is my code
public class GMap extends FragmentActivity implements LocationListener{
public static GoogleMap mMap;
LocationManager locationManager;
Criteria criteria;
String provider;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gmap);
setUpMapIfNeeded();
}
#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) {
setUpMapIfNeeded();
}
}
}

Categories

Resources