I'm using this code, and I'm getting false value in
if(intent.getAction().equals(Intent.ACTION_SEARCH))
this condition, so Search view is not working. Appreciate any help.
MapsActivity
public class MapsActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor>,OnMapReadyCallback {
private GoogleMap mMap;
private PopupMenu supportMenuInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = fragment.getMap();
Log.e("MAP"," load");
handleIntent(getIntent());
}
private void handleIntent(Intent intent){
Log.e("handle intent"," load"+intent);
Log.e("handle intent"," rate "+intent.getAction().equals(Intent.ACTION_SEARCH));
if(intent.getAction().equals(Intent.ACTION_SEARCH))
{
Log.e("handle intent"," if"+intent.getAction().equals(Intent.ACTION_SEARCH));
doSearch(intent.getStringExtra(SearchManager.QUERY));
}
else if(intent.getAction().equals(Intent.ACTION_VIEW))
{
Log.e("handle intent"," else if");
getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}
else
{
Log.e("handle intent"," else");
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
private void doSearch(String query){
Log.e("Dosearch"," load "+query);
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(0, data, this);
}
private void getPlace(String query){
Log.e("getPlace"," load "+query);
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(1, data, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
getMenuInflater().inflate(R.menu.main, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setIconifiedByDefault(false);
search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String query) {
doSearch(query);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
});
}
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
onSearchRequested();
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle query) {
CursorLoader cLoader = null;
if(arg0==0)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ query.getString("query") }, null);
else if(arg0==1)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString("query") }, null);
return cLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
showLocations(c);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
private void showLocations(Cursor c){
MarkerOptions markerOptions = null;
LatLng position = null;
mMap.clear();
while(c.moveToNext()){
markerOptions = new MarkerOptions();
position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
markerOptions.position(position);
markerOptions.title(c.getString(0));
mMap.addMarker(markerOptions);
}
if(position!=null){
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
mMap.animateCamera(cameraPosition);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
Log.e("OnReady", String.valueOf(sydney));
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Error Was in Manifest file
enter code here
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!-- Protect the map component of the application using application signature -->
<permission
android:name="com.example.user.demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<!-- Allows to receive map -->
<uses-permission android:name="com.example.user.demo.MAPS_RECEIVE" />
<!-- Used by the Google Maps Android API V2 to download map tiles from Google Maps servers -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Allows the Google Maps Android API V2 to cache map tile data in the device's external storage area -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Allows the Google Maps Android API V2 to use WiFi or mobile cell data (or both) to determine the device's location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Allows the Google Maps Android API V2 to use the Global Positioning System (GPS)
to determine the device's location to within a very small area -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Allows to contact Google Serves -->
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!-- Google Maps Android API V2 requires OpenGL ES version 2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat" >
<activity
android:name=".MapsActivity"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<!-- Points to searchable activity -->
<meta-data android:name="android.app.default_searchable"
android:value=".MainActivity" />
<!-- Points to searchable meta data -->
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
<provider
android:name=".PlaceProvider"
android:authorities="com.example.user.demo.PlaceProvider"
android:exported="false" />
<!-- Specifies the Android API Key, which is obtained from Google API Console -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="--------------------------------" />
</application>
Related
I'm developing an Android application which requires Google maps to be loaded in a fragment.
The map loads only partially. Half of the map remains gray and doesn't load.
Please provide your suggestions. I'm not sure about the issue.
Below are the project files :
MapFragment.java:
public class MapFragment extends Fragment {
MapView mMapView;
GoogleMap googleMap;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
context = getContext();
DatabaseHelper databaseHelper = new DatabaseHelper(context, null, null, 0);
ArrayList<PropertyDetails> arrayList = databaseHelper.readData();
Log.d("PAVAN", "Details "+arrayList.get(0).getCity());
Log.d("PAVAN", "Details "+arrayList.get(0).getLatitude());
googleMap = mMapView.getMap();
for(int i = 0 ; i < arrayList.size() ; i++) {
// latitude and longitude
String PropertyType = arrayList.get(i).PropertyType;
String Address = arrayList.get(i).Address;
String City = arrayList.get(i).City;
Double LoanAmount = arrayList.get(i).LoanAmount;
Double APR = arrayList.get(i).APR;
Double MonthlyPayment = arrayList.get(i).MonthlyPayment;
Double Latitude = arrayList.get(i).getLatitude();
Double Longitude = arrayList.get(i).getLongitude();
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(Latitude, Longitude)).title(PropertyType + "<br/>" + Address + "<br/>" +
City + '\n' + LoanAmount + '\n' + APR + "<br/>" + MonthlyPayment).snippet("" + APR).snippet("" + MonthlyPayment);
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
// googleMap.setInfoWindowAdapter(CustomWindowAdapter);
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
fragment_map.xml
<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"
android:paddingTop="8dp"
tools:context="com.example.pavanshah.mortgagecalculator.MainActivity$PlaceholderFragment">
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<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"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<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.gms.version"
android:value="#integer/google_play_services_version">
</meta-data>
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="My_Key">
</meta-data>
</application>
Screenshots:
Hi I am trying to getting location(latitude and longitude) from Gps and set marker on google map but it is not working.In this code I am trying to get latitude and longitude from gps Location Listener method onLocationChanged but this method never calling not showing any toast.
public class MapsFragment extends Fragment implements OnMapReadyCallback, GoogleMap.OnMapLoadedCallback {
private static View view;
private SupportMapFragment mMap;
private static Double latitude = 28.6538100, longitude = 77.2289700;
GoogleMap gMap;
private static final int PERMISSION_REQUEST_CODE = 1;
private MinDisLocationListener locationListener;
private LocationManager lm;
public MapsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentManager fm = getActivity().getSupportFragmentManager();
SupportMapFragment mMapFragment = (SupportMapFragment) getActivity()
.getSupportFragmentManager().findFragmentById(R.id.map);
locationListener = new MinDisLocationListener();
lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2, this.locationListener);
} else {
requestPermission();
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2, this.locationListener);
if (mMapFragment == null) {
mMapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, mMapFragment).commit();
mMapFragment.getMapAsync(this);
}
view = inflater.inflate(R.layout.fragment_map, container, false);
return view;
}
#Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.setOnMapLoadedCallback(this);
// drawMarker(latitude, longitude);
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(49.39, -124.83), 20));
gMap.addMarker(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183))
.title("San Francisco")
.snippet("Population: 776733"));
gMap.getUiSettings().setZoomGesturesEnabled(true);
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
gMap.setMyLocationEnabled(true);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2, this.locationListener);
} else {
requestPermission();
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
mMap = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (mMap != null) {
mMap = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, mMap).commit();
mMap.getMapAsync(this);
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(getActivity(), "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
}
public void drawMarker(double lat, double lon) {
if (gMap != null) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lon)).title(" Maps Tutorial").snippet("Android Ruler");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
gMap.addMarker(marker);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
gMap.setMyLocationEnabled(true);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000, 2, this.locationListener);
}
gMap.setMyLocationEnabled(true);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2, this.locationListener);
} else {
}
break;
}
}
#Override
public void onResume() {
super.onResume();
FragmentManager fm = getChildFragmentManager();
mMap = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (mMap != null) {
mMap = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, mMap).commit();
mMap.getMapAsync(this);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (mMap != null) {
mMap = null;
}
}
#Override
public void onMapLoaded() {
}
public class MinDisLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Log.d("location", "onLocationChanged");
drawMarker(location.getLatitude(),location.getLongitude());
Toast.makeText(getActivity(), "onLocationChanged", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("location", "onStatusChanged");
Toast.makeText(getActivity(), "onStatusChanged", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Log.d("location", "onProviderEnabled");
Toast.makeText(getActivity(), "onProviderEnabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Log.d("location", "onProviderEnabled");
Toast.makeText(getActivity(), "onProviderEnabled", Toast.LENGTH_SHORT).show();
}
}
}
Msnifist File Is this
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.deltastar.catchme" >
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permisssion.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
- See more at:
http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample#sthash.PtrAvZrk.dpuf
<application
android:allowBackup="true"
android:icon="#drawable/ic_logo"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".LoginActivity" />
<activity
android:name=".RegisterActivity"
android:label="#string/register" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".OtpVerifyActivity"
android:label="#string/otp_verify" />
<activity android:name=".CreateProfileActivity" />
<activity android:name=".ChatMemberActivity" />
<activity android:name=".CreateGroup" />
<activity android:name=".AddMemberGroup" />
<activity android:name=".MeatPointName" />
<activity android:name=".MyMeeting" />
<activity android:name=".ChatActivity" />
<activity android:name=".GroupInfo" />
<activity
android:name=".MapChat"
android:label="#string/title_activity_map_chat" />
<activity android:name=".MyMeatingReq" />
<activity android:name=".UserProfile" />
<activity android:name=".MyProfile" />
<activity android:name=".SplashScreen" />
<activity android:name=".Settings" />
<activity
android:name=".DrawerDemo"
android:label="#string/title_activity_drawer_demo"
android:theme="#style/AppTheme" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MeetingPointLocation"
android:label="#string/title_activity_create_meating_point" />
<!--
ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information.
-->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".HomePage"
android:label="#string/title_activity_home_page"
android:theme="#style/AppTheme" />
<activity android:name=".MyLocation" />
<activity android:name="com.services.LocDemo" >
</activity>
</application>
</manifest>
fragment_map.xml
<FrameLayout 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="com.fragment.MapsFragment">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
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="match_parent" />
</FrameLayout>
Your code works perfect. You just have to move your device in the place where gps is available, because the place where you are testing your app may not have exposure to GPS satellite.
onLocationChanged() will be called once GPS is detected by the device
Check your project from there
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
But i think problem with manifest
Have you this
<permission android:name="tj.tajdev.mrking.whatisonindushanbe.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="tj.tajdev.mrking.whatisonindushanbe.permission.MAPS_RECEIVE" /> <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" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
And this
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
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
I implemented a map method using the Google Maps API. Yesterday, it was working fine. Since then, I've made absolutely no changes whatsoever to eclipse, any map related method (including views and the MapActivity class) or anything in the its corresponding entry in the manifest - the only thing I changed was to add a splash screen, thereby changing the launcher activity from MyLITactivity to SplashActivity.
My API key is in the manifest, and I've included the uses-library entry in the manifest.
When I run the app, logcat shows this:
05-06 16:12:04.855: I/dalvikvm(753): Failed resolving Lcom/mad/mylit/MapActivity; interface 486 'Lcom/google/android/gms/maps/GoogleMap$OnMapClickListener;'
05-06 16:12:04.855: W/dalvikvm(753): Link of class 'Lcom/mad/mylit/MapActivity;' failed
05-06 16:12:04.855: E/dalvikvm(753): Could not find class 'com.mad.mylit.MapActivity', referenced from method com.mad.mylit.MyLITactivity.startMaps
05-06 16:12:04.855: W/dalvikvm(753): VFY: unable to resolve const-class 495 (Lcom/mad/mylit/MapActivity;) in Lcom/mad/mylit/MyLITactivity;
05-06 16:12:04.855: D/dalvikvm(753): VFY: replacing opcode 0x1c at 0x0002
My manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mad.mylit"
android:installLocation="auto"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
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-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/lit_logo"
android:label="#string/app_name"
android:theme="#style/Theme.litac" >
<activity
android:name="com.mad.mylit.MyLITactivity"
android:label="#string/app_name"
android:theme="#style/Theme.litac" >
</activity>
<activity
android:name="com.mad.mylit.ItemListActivity"
android:label="#string/title_item_list" >
</activity>
<activity
android:name="com.mad.mylit.ItemDetailActivity"
android:label="#string/title_item_detail"
android:parentActivityName=".ItemListActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ItemListActivity" />
</activity>
<activity
android:name="com.mad.mylit.NewsDetailFragment"
android:label="#string/title_activity_news_detail_fragment" >
</activity>
<activity
android:name="com.mad.mylit.NewsListFragment"
android:label="#string/title_activity_news_list_fragment" >
</activity>
<activity
android:name="com.mad.mylit.NewsActivity"
android:label="#string/title_activity_news" >
</activity>
<activity
android:name="com.mad.mylit.DetailActivity"
android:label="SU News" >
</activity>
<activity
android:name="com.mad.mylit.TimetableActivity"
android:label="#string/title_activity_timetable" >
</activity>
<activity
android:name="com.mad.mylit.MoodleActivity"
android:label="#string/title_activity_moodle" >
</activity>
<activity
android:name="com.mad.mylit.SplashActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="com.google.android.maps" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="xxxxxxxxxxxxxxxxxxxxx" />
<activity
android:name="com.mad.mylit.MapActivity"
android:label="#string/title_activity_map"
android:parentActivityName="com.mad.mylit.MyLITactivity" >
android:theme="#style/Theme.litac"
android:uiOptions="splitActionBarWhenNarrow" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.mad.mylit.MyLITactivity" />
</activity>
</application>
</manifest>
MapActivity:
public class MapActivity extends FragmentActivity implements OnMapClickListener, OnMapLongClickListener{
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Location myLocation;
LocationManager locationManager;
String provider;
OnLocationChangedListener myLocationListener = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setupActionBar();
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myMap.setOnMapClickListener(this);
myMap.setOnMapLongClickListener(this);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
public void activate(OnLocationChangedListener listener) {
myLocationListener = listener;
}
public void deactivate() {
myLocationListener = null;
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(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.maps, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.menu_legalnotices:
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MapActivity.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
case R.id.itemid_1:
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=Limerick Institute of Technology, Limerick"));
startActivity(i);
return true;
case R.id.itemid_2:
//TODO change to local map of LIT
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
public void onLocationChanged(Location location) {
myLocationListener.onLocationChanged(location);
LatLng latlng = new LatLng(location.getLatitude(),location.getLongitude());
myMap.animateCamera(CameraUpdateFactory.newLatLng(latlng));
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onMapLongClick(LatLng point) {
//myMap.addMarker(new MarkerOptions().position(point).title(point.toString()));
}
#Override
public void onMapClick(LatLng point) {
//myMap.animateCamera(CameraUpdateFactory.newLatLng(point));
}
}
If I comment out the OnMapClickListener and OnMapLongClickListener implements (and their corresponding methods) the error disappears.
Solved: I removed and re-imported all libraries, fixed project properties and did a clean-build.
Still have no idea why it worked yesterday and not today...
Here is my manifest file:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-library android:name="com.google.android.maps"/>
<activity
android:name="com.docuart.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>
</application>
</manifest>
And Here is my layout:
<?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" >
<com.google.android.maps.MapView
android:id="#+id/mapGoogle"
android:enabled="true"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="my api key" />
</LinearLayout>
Here is my code:
public class MainActivity extends MapActivity {
private static final int MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;//metre
private static final int MINIMUM_TIME_BETWEEN_UPDATES = 1000;//milisaniye
protected LocationManager locationManager;
MapView mView;
MapController mapController;
GeoPoint gPoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mView = (MapView) findViewById(R.id.mapGoogle);
mView.displayZoomControls(true);
mView.setBuiltInZoomControls(true);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES , MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
gPoint = new GeoPoint((int)(location.getLatitude()*1000000),(int)(location.getLongitude()*1000000));
mapController = mView.getController();
mapController.animateTo(gPoint);
mapController.setZoom(14);
}
}
#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;
}
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
gPoint = new GeoPoint((int)(location.getLatitude()*1000000),(int)(location.getLongitude()*1000000));
mapController = mView.getController();
mapController.animateTo(gPoint);
mapController.setZoom(14);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}}
protected boolean isRouteDisplayed() {
return false;
}
}
Project running but i cant see my location. I cant find where is may fault. To see Screenshot: http://sdrv.ms/Wyf1Z1 Thank u for helping.
in your layout add your actual 2.0 auth api key in android:apiKey="my api key" />, which you must be reated from api key console .