I am having some prolems with my google maps app. For now the app was only suppost to get my location em zoom in it, but is not working. My location aways ends in the top of the map. Here is my code:
MainActivity:
public class MainActivity extends Activity implements LocationListener {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isGooglePlayOk()) {
setContentView(R.layout.activity_main);
setMap();
googleMap.setMyLocationEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_legalnotices:
startActivity(new Intent(this, LegalNoticeActivity.class));
return true;
default:
return false;
}
}
private boolean isGooglePlayOk() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS) {
return (true);
}
else {
((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10))
.show();
}
return (false);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.main.map)).getMap();
if (googleMap != null) {
}
googleMap.setMyLocationEnabled(true);
LocationManager la = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = la.getBestProvider(new Criteria(), true);
Location loc = la.getLastKnownLocation(provider);
if (provider != null) {
onLocationChanged(loc);
}
googleMap.setOnMapLongClickListener(onLongClickMapSettiins());
}
}
private OnMapLongClickListener onLongClickMapSettiins() {
// TODO Auto-generated method stub
return new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
Toast.makeText(getApplicationContext(), "OK",
Toast.LENGTH_SHORT).show();
}
};
}
#Override
public void onLocationChanged(Location location) {
LatLng latlong = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.setMyLocationEnabled(true);
CameraPosition cp = new CameraPosition.Builder().target(latlong)
.zoom(15).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+main/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mapateste"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!--
The following two 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" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="(My Api is working fine)" />
<activity
android:name="com.example.mapateste.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.mapateste.LegalNoticeActivity"
android:label="#string/title_activity_legal_notice" >
</activity>
</application>
I can only test in my device. The map is working fine but i cannot get my position on the center of the screen right away only clicking at the mylocationbutton. Somebody can help me?
Just declare a point where you want to center your point.
LatLng cur_Latlng = new LatLng(21.0000, 78.0000);
gm.moveCamera(CameraUpdateFactory.newLatLng(cur_Latlng));
gm.animateCamera(CameraUpdateFactory.zoomTo(4));
the desired zoom level is in the range of 2.0 to 21.0.
// try this
#Override
public void onLocationChanged(Location location) {
LatLng latlong = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
googleMap.animateCamera(CameraUpdateFactory.zoomBy(15));
}
Your min sdk is 8. You should use SupportMapFragment. Your class must extend FragmentActivtiy
Check the line above developers guide heading in the below link
https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapFragment
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Use SupportMapFragment
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap mMap = fm.getMap();
Make sure you have added support library
Also make sure you imported the below
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment
To zoom
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlong,20);
googleMap.moveCamera(update);
This is working Current Location with zoom for Google Map V2
double lat= location.getLatitude();
double lng = location.getLongitude();
LatLng ll = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
Note that the My Location layer does not return any data. If you wish to access location data programmatically, use the Location API.
In your MainActivity (onCreate Method)
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(MainActivity.this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
On method onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
GoogleMap mMap = googleMap;
// Set blue point on the map at your cuurent location
mMap.setMyLocationEnabled(true);
// Show zoon controls on the map layer
mMap.getUiSettings().setZoomControlsEnabled(true);
//Show My Location Button on the map
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
on method onConnected
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
LocationListener.latlonInit= new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());
CameraPosition target = CameraPosition.builder().tilt(66.0f).target(LocationListener.latlonInit)
.zoom(MainActivity.ZOOM).build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(target));
}
}
You class should extend Fragment Activity
public class MainActivity extends FragmentActivity {
//assign any arbitrary value to GPS_ERRODIALOG_REQUEST
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap googlemap;
}
for Google Service Ok method I would do Following:
public boolean isGooglePlayOk(){
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable)){
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(this, "Can't connect to Goolge Play", Toast.LENGTH_SHORT).show();
}
return false;
}
In the .xml file, when you declare the fragment, you need to support Map Fragment since your min skd is 8:
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:maps="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
activity_map.xml is for displaying map if condition is true for setMap else go to you regular activity_main.xml.
public class MainActivity extends FragmentActivity {
GoogleMap mMap;
if (isGooglePlayOk()) {
setContentView(R.layout.activity_map);
if (setMap()) {
mMap.setMyLocationEnabled(true);
}
else {
//your code
}
}
else {
setContentView(R.layout.activity_main);
}
method for setMap:
private boolean setMap() {
if (mMap == null) {
SupportMapFragment mapFrag =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
If you want to automatically zoom to some point in google maps v2 u can do like this
private float previousZoomLevel = 13.00f;
LatLng zoomPoint = new LatLng(12.977286, 77.632720);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(zoomPoint,previousZoomLevel));
here previousZoomLevel is level of zoom
Related
I want to zoom to the current location of user when activity started. I have two java class. One of is MapActivity.java and the other is MapFragment.java. I'm trying to do this job on MapFragment.java.
private Actvity activity;
private volatile GoogleMap googleMap;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}
MapFragment.java/onMapReady ;
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
mGoogleApiClient=new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API)
.addConnectionCallbacks(activity)
.addOnConnectionFailedListener(activity)
.build();
mGoogleApiClient.connect();
}
In this onMapReady, .addConnectionCallbacks(activity) and .addOnConnectionFailedListener(activity) are giving warning like in the image;
enter image description here
In the examples that I have analyzed before they are implementing GoogleApiClient.ConnectionCallbacks and GoogleApiCleint.OnConnectionFailedListener not casting. Without implementing, I couldn't get these functions;
#Override
public void onConnected(Bundle bundle) {
mLocationRequest=LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
And also I have to get LocationListeners's method;
#Override
public void onLocationChanged(Location location) {
if(location == null){
Toast.makeText(this,"Cant get current location",Toast.LENGTH_LONG).show();
}
else{
LatLng ll= new LatLng(location.getLatitude(),location.getLongitude());
CameraUpdate update= CameraUpdateFactory.newLatLngZoom(ll,15);
mGoogleMap.animateCamera(update);
}
}
If I implement them by hand in the fragment, does it cause any problem? What is the proper way to get current location in fragment activity?
If I implement them by hand in the fragment, does it cause any
problem?
No. All you need to do is implement ConnectionCallbacks and OnConnectionFailedListener.
What is the proper way to get current location in fragment activity?
public class MyFragment extends Fragment implements
ConnectionCallbacks, OnConnectionFailedListener {
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient); // this is your location
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}
Reference
I have implemented a Fragment in Activity and Location listener and MapReady is called in fragment to get current location. Refer the below code.
MainActivity.Java
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setFragment(new MapFragment());
}
// class for being re-used by several instances
protected void setFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
}
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout
android:id="#+id/frame_containerone"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/imagenext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
/>
</RelativeLayout>
MapFragment.Java
public class MapFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, OnMapReadyCallback {
private static final String TAG = "MapFragment";
MainActivity mActivity;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
SupportMapFragment mapFragment;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_fragment, null, true);
mActivity = ((MainActivity) getActivity());
initViews(view);
return view;
}
private void initViews(View view) {
mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(mActivity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
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.
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);// mapFragment.getMapAsync((OnMapReadyCallback) mActivity);
}
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
}
map_fragment.xml
<?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 xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
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="388dp"
android:layout_weight="0.40" />
</LinearLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.theme.fragment">
<permission
android:name="com.theme.fragment.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.theme.fragment.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Goolge API Key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your_Api key" />
</application>
</manifest>
I am trying to create a map activity that displays the user current location that can be zoomed to street level but my app is not working properly, what do you think are the codes that I need to add?
public class Map_Activity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener{
private GoogleMap myMap;
private LocationClient myLocationClient;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000)
.setFastestInterval(16)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getMapReference();
}
#Override
protected void onResume(){
super.onResume();
getMapReference();
wakeUpLocationClient();
myLocationClient.connect();
}
#Override
public void onPause(){
super.onPause();
if (myLocationClient != null){
myLocationClient.disconnect();
}
}
private void gotoMyLocation(double lat, double lng) {
changeCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(new LatLng(lat, lng))
.zoom(15.5f)
.bearing(0)
.tilt(25)
.build()
), new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {
}
#Override
public void onCancel() {
}
});
}
private void wakeUpLocationClient(){
if(myLocationClient == null){
myLocationClient = new LocationClient(getApplicationContext(),this,this);
}
}
private void getMapReference(){
if(myMap==null){
myMap = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
}
if (myMap != null){
myMap.setMyLocationEnabled(true);
}
}
#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_map, menu);
return true;
}
#Override
public void onConnected(Bundle bundle){
myLocationClient.requestLocationUpdates( REQUEST, this);
}
#Override
public void onDisconnected(){
}
#Override
public void onLocationChanged(Location location){
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult){
}
#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);
}
private void changeCamera(CameraUpdate update, GoogleMap.CancelableCallback callback) {
myMap.moveCamera(update);
}
}
the app is running but the map is not showing and it is not showing me my current location :( i hope somebody could help me
Here are step by step for using GoogleMaps:
A.configured your project to work with GoogleMaps (your map may not appear if not properly configured):
in "build.graddle" add dependencies with proper version e.g. 6.5.87 or 8.1.0:
compile 'com.google.android.gms:play-services:8.1.0'
in "Android.Manifest" add permissions, GL and API Key (make sure to put your APIKey):
< uses-permission android:name="android.permission.WAKE_LOCK" />
< uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
< uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
< uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
< uses-permission android:name="android.permission.INTERNET" />
< uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
< uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<!-- Google Maps Fragment API Key Data -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOUR API KEY" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
B. Code:
use OnMapReady :
add "OnMapReadyCallback" to your activity class:
public class Map_Activity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener,
OnMapReadyCallback
{
override onMapReady to enable location and have reference to GoogleMap:
#Override
public void onMapReady(GoogleMap map) {
map.setMyLocationEnabled(true);
googleMap = map;
}
in Activity-OnCrate call getMapAsync:
FragmentManager fm = getSupportFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
C. Remove/replace deprecated code:
-LocationClient
-replace "GooglePlayServicesClient" with GoogleApiClient
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" />
I'm trying to show the map from the Google Maps API V2 in fragment. I tried with the SupportMapFragment, but I can't get the expected output.
Also I'm a beginner on this platform! What I really want is just a way to put a map from the Google Maps API V2 for Android in a fragment. Please share your ideas and references.
Thanks in Advance !
Here is the code,
public class YourFragment extends Fragment {
// ...
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.yourlayout, null, false);
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
//...
return v;
}
Your layout,
<RelativeLayout 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"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Make some changes in your manifest file also.Like,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp.android.locationapi.maps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<permission
android:name="com.myapp.android.locationapi.maps.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.myapp.android.locationapi.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.myapp.android.locationapi.maps.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_apikey" />
</application>
</manifest>
public class DemoFragment extends Fragment {
MapView mapView;
GoogleMap map;
LatLng CENTER = null;
public LocationManager locationManager;
double longitudeDouble;
double latitudeDouble;
String snippet;
String title;
Location location;
String myAddress;
String LocationId;
String CityName;
String imageURL;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater
.inflate(R.layout.fragment_layout, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
setMapView();
}
private void setMapView() {
try {
MapsInitializer.initialize(getActivity());
switch (GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getActivity())) {
case ConnectionResult.SUCCESS:
// Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT)
// .show();
// Gets to GoogleMap from the MapView and does initialization
// stuff
if (mapView != null) {
locationManager = ((LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE));
Boolean localBoolean = Boolean.valueOf(locationManager
.isProviderEnabled("network"));
if (localBoolean.booleanValue()) {
CENTER = new LatLng(latitude, longitude);
} else {
}
map = mapView.getMap();
if (map == null) {
Log.d("", "Map Fragment Not Found or no Map in it!!");
}
map.clear();
try {
map.addMarker(new MarkerOptions().position(CENTER)
.title(CityName).snippet(""));
} catch (Exception e) {
e.printStackTrace();
}
map.setIndoorEnabled(true);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.zoomTo(5));
if (CENTER != null) {
map.animateCamera(
CameraUpdateFactory.newLatLng(CENTER), 1750,
null);
}
// add circle
CircleOptions circle = new CircleOptions();
circle.center(CENTER).fillColor(Color.BLUE).radius(10);
map.addCircle(circle);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
} catch (Exception e) {
}
}
in fragment_layout
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_marginRight="10dp" />
Update 10/24/2014 This is all wrong. You shouldn't have a fragment in a fragment. Rather you should extend the SupportMapFragment. See this stackoverflow post for some details: https://stackoverflow.com/a/19815266/568197
here is my onDestroyView()
public void onDestroyView() {
super.onDestroyView();
if (mMap != null) {
getFragmentManager()
.beginTransaction()
.remove(getFragmentManager().findFragmentById(R.id.map))
.commit();
}
}
in addition to the answer above, I also had to put the following lines to my manifest
<!-- inside <aplication> tag -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
And I also changed the layout to use SupportMapFragment instead of MapFragment
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
Here is my code.
Create project in google map concole and generate api key.
and then add dependency to build.gradle(app level).
compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.google.android.gms:play-services-places:10.2.1'
remember to add permissions in Android.manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-feature android:name="android.hardware.location.gps" android:required="true"/>
create activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame">
<fragment
class="com.googlelocationmapdemo.FragmentLocation"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
nothing to call from MainActivity.class
Create fragment_location.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearMap"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Create FragmentLocation.class
public class FragmentLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static final String TAG = FragmentLocation.class.getSimpleName();
public static final int REQUEST_CODE_FOR_PERMISSIONS = 1;
GoogleApiClient mGoogleApiClient;
LatLng mLatLng;
GoogleMap mGoogleMap;
Marker mCurrLocationMarker;
private LinearLayout linearMap;
Location mLastLocation;
LocationManager locationManager;
boolean statusOfGPS;
private Dialog mDialogGPS;
View view;
LocationRequest mLocationRequest;
SupportMapFragment mFragment;
FragmentManager fragmentManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_location,container,false);
fragmentManager=getChildFragmentManager();
mFragment = (SupportMapFragment)fragmentManager.findFragmentById(R.id.map);
mFragment.getMapAsync(this);
if (!isGooglePlayServicesAvailable()) {
Toast.makeText(getActivity(), "play services not available", Toast.LENGTH_SHORT).show();
}
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return view;
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000); //5 seconds
mLocationRequest.setFastestInterval(2000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mLatLng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
// Zoom in the Google Map
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION
, Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_FOR_PERMISSIONS);
}
} else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
//show dialog when click on location top-right side located on map.
mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!statusOfGPS) {
turnOnGps();
} else {
getCurrentLocation(mLastLocation);
}
return false;
}
});
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
return false;
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_FOR_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
if (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)) && (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)))) {
Snackbar snackbar = Snackbar.make(linearMap, "Never asked"
, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("Allow", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
});
snackbar.show();
}
}
break;
}
}
private void getCurrentLocation(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
if (locationManager != null) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);//getting last location
}
if (mLastLocation != null) {
if (mGoogleMap != null) {
Log.d("activity", "LOC by Network");
mLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mLatLng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
}
}
private void turnOnGps() {
if (mGoogleMap != null) {
mGoogleMap.clear();
}
statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);//getting status of gps whether gps is on or off.
mDialogGPS = new Dialog(getActivity(), R.style.MyDialogTheme);
mDialogGPS.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialogGPS.setContentView(R.layout.dialog_turnongps);
TextView txtCancel = (TextView) mDialogGPS.findViewById(R.id.txtCancel);
TextView txtOK = (TextView) mDialogGPS.findViewById(R.id.txtSetting);
ImageView imgLocation = (ImageView) mDialogGPS.findViewById(R.id.imgLocation);
imgLocation.setImageResource(R.drawable.ic_location_my);
txtCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDialogGPS.dismiss();
//finish();
if (!statusOfGPS) {
getCurrentLocationByDefault();
} else {
getCurrentLocation(mLastLocation);
}
}
});
txtOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//It is use to redirect to setting->location to turn on gps when press ok.
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
mDialogGPS.dismiss();
if (!statusOfGPS) {
getCurrentLocationByDefault();
} else {
getCurrentLocation(mLastLocation);
}
}
});
mDialogGPS.show();
}
private void getCurrentLocationByDefault() {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
if (mGoogleMap != null) {
LatLng xFrom1 = new LatLng(0.0, 0.0);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xFrom1, (float) 0.0));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(xFrom1);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_taxi));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
} else {
Log.i("MainActivity", "getCurrentLocationByDefault else");
}
}
#Override
public void onResume() {
super.onResume();
statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (mDialogGPS != null) {
if (mDialogGPS.isShowing()) {
mDialogGPS.dismiss();
}
}
if (!statusOfGPS) {
turnOnGps();
} else {
getCurrentLocation(mLastLocation);
}
}
protected synchronized void buildGoogleApiClient() {
if (mGoogleApiClient != null) {
mGoogleApiClient = null;
}
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
create dailog_gps.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/txtPhoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Use Location?"
android:textColor="#android:color/black"
android:textSize="16sp"
/>
</LinearLayout>
<LinearLayout
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="This app wants to change your \ndevice settings:"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_marginTop="10dp"
android:weightSum="2"
android:gravity="center"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imgLocation"
android:layout_weight="1"
android:layout_gravity="top"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Use GPS, Wi-Fi and mobile \nnetwork for location"
android:layout_marginLeft="20dp"
android:textSize="12sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:orientation="horizontal"
android:layout_marginTop="20dp">
<TextView
android:id="#+id/txtCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NO"
android:layout_marginRight="30dp"
android:textSize="16sp" />
<TextView
android:id="#+id/txtSetting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="YES"
android:layout_marginRight="30dp"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
Hope this will help you :-)
Use SupportMapFragment instead of MapFragment and use getActivity()
This is a basic example using SupportMapFragment:
public class MainActivity extends ActionBarActivity implements OnMapReadyCallback{
private SupportMapFragment map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
map.getMapAsync(this);//remember getMap() is deprecated!
}
#Override
public void onMapReady(GoogleMap map) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(47.17, 27.5699), 16));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(47.17, 27.5699))); //Iasi, Romania
map.setMyLocationEnabled(true);
}
}
and change the reference in your layout:
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
For all those friends who are facing the problem:-
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()
Please try integrate GoogleMap using code
FragmentManager fm = getChildFragmentManager();
googleMap = ((SupportMapFragment)fm.findFragmentById(R.id.googleMap)).getMap();
I've the same issue , I use this code but I still get this error :
unable to instantiate fragment com.google.android.gsm.SupportMapFragment: make sure class name exists ,is public, and has empty construct or that is public
I solved it from here : How to put Google Maps V2 on a Fragment Using ViewPager
If you are using android studio create google mapsactivity its default map fragment and generate your map API KEY and do your stuff......
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
and our override method
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng map = new LatLng(lat, lon);
mMap.addMarker(new MarkerOptions().position(map).title("your title"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(map));
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
}
This example was build from the auto generated code from android studio, you dont need to change nothing in maps activity, only the context in the layout file to match your maps Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="300dp"
tools:context="com.gearwell.app.gpsmaps02.Gpsenmapa"
/>
<LinearLayout
android:id="#+id/layButtonH"
android:layout_height="150dp"
android:layout_marginTop="50dp"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_weight="0.15">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Obtener Ubicacion"
android:id="#+id/btnLocation"
android:onClick="onClick"/>
</LinearLayout>
</LinearLayout>
Using MapView within Fragment under Google Maps Android API v2.0
public class MapFragment extends Fragment {
MapView m;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.map_fragment, container, false);
m = (MapView) v.findViewById(R.id.mapView);
m.onCreate(savedInstanceState);
return v;
}
#Override
public void onResume() {
super.onResume();
m.onResume();
}
#Override
public void onPause() {
super.onPause();
m.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
m.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
m.onLowMemory();
}
}
http://ucla.jamesyxu.com/?p=287
Im not sure whats wrong but Im trying to get my google maps fragment to zoom in to a particular location on start. For some reason, it is not working and still zooms in to africa by default. Here is my code.
public class OutbreakMap extends Activity implements LocationListener {
double lat=50;
double longi=50;
private LocationManager locationManager;
private String provider;
private MapFragment mMapFragment;
private GoogleMap googleMap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set title
alertDialogBuilder.setTitle("Turn On Your GPS");
// set dialog message
alertDialogBuilder
.setMessage("Please turn on your GPS to track sickness in your area!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
OutbreakMap.this.finish();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(),"Location not found",Toast.LENGTH_SHORT);
}
mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map, mMapFragment);
fragmentTransaction.commit();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
setUpMapIfNeeded();
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
if(location != null) {
lat=location.getLatitude();
longi=location.getLongitude();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat,longi)) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
// Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
UiSettings uiSettings=googleMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(),"Couldn't Find Location",Toast.LENGTH_SHORT);
}
ParseGeoPoint userLoc= new ParseGeoPoint(lat,longi);
ParseQuery query= new ParseQuery("Outbreak");
query.whereWithinMiles("location",userLoc,1);
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
GetOutbreaks.getOutBreaksNearMe(googleMap,lat,longi,objects);
Toast.makeText(getApplicationContext(),"Recieved Outbreak Data",Toast.LENGTH_SHORT);
} else {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could Not Download Data",Toast.LENGTH_SHORT);
}
}
});
// moveToPrescription();
// moveToPrescription();
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void moveToPrescription(){
Intent intent = new Intent(this,Prescription.class);
startActivity(intent);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (googleMap != null) {
// The Map is verified. It is now safe to manipulate the map.
}
}
}
}
Also, here is my xml layout for the map fragment activity
<?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 xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
</LinearLayout>
And my Android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.parse.starter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15"/>
<permission
android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- The following two 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"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:name="ParseApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".ParseStarterProjectActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Register"/>
<activity android:name=".Login"/>
<activity android:name=".Home"/>
<activity android:name=".OutbreakMap"/>
<activity android:name=".Prescription"/>
<activity android:name=".MyPrescriptions"/>
<receiver android:name=".AlarmManagerBroadcastReceiver"></receiver>
<uses-library android:name="com.google.android.maps"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="My Maps API Key is Here"/>
</application>
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
</manifest>
The LogCat is not showing any errors. Thanks for the help!
You are adding second SupportMapFragment in code on top of Fragment having GoogleMap you interact with. Just remove unnecessary code.
Use SupportMapFragment
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
GoogleMap gm;
gm = ((SupportMapFragment(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();
Comment out the following lines of code
mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map, mMapFragment);
fragmentTransaction.commit();
and its going to work like a charm.