Google map app crashes on android OS 4.3 - android

I built an app for map. Added all the necessary permissions and generated the api key but it is still crashing. I am working on command line and implemented it on Android 4.3 OS.
Here is the code:
public class MainActivity extends FragmentActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Manifest File
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<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"/>
<!-- 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"/>
<permission
android:name="mapdemo.exp.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="mapdemo.exp.permission.MAPS_RECEIVE"/>
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity android:name="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="AIzaSyAS08XqNbdRuxsOwNrosza0WE2mijfdoO8"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="4323000" />
</application>
Tried this
public class ActivityMain extends Activity
{
public GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
{
Log.e("loading map. . . .", "loading map. . . ");
initilizeMap();
}
catch (Exception e)
{
Log.e("catch. . .", "catch. . .");
e.printStackTrace();
}
}
private void initilizeMap()
{
Log.e("initializing map. . . ", "initializing map. . ");
if (googleMap == null)
{
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (googleMap == null)
{
Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onResume()
{
super.onResume();
initilizeMap();
}
}

Try This
In 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
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"
/>
</LinearLayout>
In Activity:-
public class ActivityMain extends Activity {
// Google Map
public GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Log.e("loading map. . . .", "loading map. . . ");
// Loading map
initilizeMap();
} catch (Exception e) {
Log.e("catch. . .", "catch. . .");
e.printStackTrace();
}
/*
* MapFunctionality mf = new MapFunctionality(); mf.currentLoc();
* mf.addMarker();
*/
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
// MapFunctionality mf = new MapFunctionality();
Log.e("initializing map. . . ", "initializing map. . ");
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
// mf.currentLoc();
// mf.addMarker();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Follow these Link 1 and Link 2
Hope it will help you to sort out with your problem
Good Luck

Related

MapView isn't showing android

I'm working with Google Maps API For Android.
I'm using a MapView since it's inside a Fragment in a ViewPager.
Unfortunately, it doesn't show as expected.
The compilator give me this error :
[doInBackground] fail to retrieve url: https://play.google.com/store/apps/details?myApp...
Why ? I'm using this in debug environment, it should look for the playstore.
Here is my manifest and my layouts:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="faurecia.captordisplayer.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="faurecia.captordisplayer.permission.MAPS_RECEIVE" />
<!-- Permission pour utiliser la connexion internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission permettant de vérifier l'état de la connexion -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Permission pour stocker des données en cache de la map -->
<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="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".Application">
<uses-library android:name="com.google.android.maps" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCKYeYG6IDbaRAs-rLmS3W_Zx8q742F5VU"/>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
my activity fragment :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.gms.maps.MapView
android:id="#+id/mapview"
android:layout_width="300px"
android:layout_height="300px"
android:apiKey="AIzaSyCKYeYG6IDbaRAs-rLmS3W_Zx8q742F5VU"/>
<faurecia.captordisplayer.view.GradientGauge
android:id="#+id/gradientGauge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<faurecia.captordisplayer.view.EnginePowerGauge
android:id="#+id/engineGauge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<faurecia.captordisplayer.view.Speedmeter
android:id="#+id/speedmeter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<faurecia.captordisplayer.view.RankingGauge
android:id="#+id/rankingGauge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
and my fragment code :
public class HMI0Fragment extends HMIFragment implements OnMapReadyCallback {
#Bind(R.id.mapview) MapView mMapView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
reScheduleTimerTask(TIMER_PERIOD);
mView = inflater.inflate(R.layout.fragment_hmi0, container, false);
ButterKnife.bind(this, mView);
mMapView.getMapAsync(this);
return mView;
}
#Override
public void onMapReady(GoogleMap map) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(-18.142, 178.431), 2));
// Polylines are useful for marking paths and routes on the map.
map.addPolyline(new PolylineOptions().geodesic(true)
.add(new LatLng(-33.866, 151.195)) // Sydney
.add(new LatLng(-18.142, 178.431)) // Fiji
.add(new LatLng(21.291, -157.821)) // Hawaii
.add(new LatLng(37.423, -122.091)) // Mountain View
);
}
}
To use the Google Maps Android API, you must register your app project on the Google Developers Console and get a Google API key which you can add to your app. The type of API key you need is an Android key.
Follow instructions here to set up a maps API key: https://developers.google.com/maps/documentation/android-api/signup#release-cert
Make a project in the Google Developers Console
Generate a key to use the Maps API
Add the key to your android manifest
Just call the onCreate() method before you call getMapAsync() and once the callback is called, you need to call onResume() on the MapView object.
public class MainActivity extends MapActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (getView() != null) {
final MapView mapView = (MapView)getView().findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng coordinates = new LatLng(match.match.LocationLatitude, match.match.LocationLongitude);
googleMap.addMarker(new MarkerOptions().position(coordinates).title(match.match.LocationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 15));
mapView.onResume();
}
}
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Here's a demo app demonstrate how to use Maps API for Android using SupportMapFragment - getMapAsync: https://github.com/googlemaps/android-samples/tree/master/ApiDemos
Thanks for the explanation but the trouble was elsewhere.
When including a MapView inside a Fragment, you have to override all the fragment state (OnResume, OnPause etc) and use the MapView.
Here is a sample :
public class HMI0Fragment extends HMIFragment implements OnMapReadyCallback {
private static int TIMER_PERIOD = 4000;
private static String NAME = "HMI0";
#Bind(R.id.mapview) MapView mMapView;
private boolean mapsSupported = true;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MapsInitializer.initialize(getActivity());
if (mMapView != null) {
mMapView.onCreate(savedInstanceState);
}
initializeMap();
}
private void initializeMap() {
if ( mapsSupported) {
mMapView = (MapView) getActivity().findViewById(R.id.mapview);
mMapView.getMapAsync(this);
//setup markers etc...
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
reScheduleTimerTask(TIMER_PERIOD);
mView = inflater.inflate(R.layout.fragment_hmi0, container, false);
ButterKnife.bind(this, mView);
return mView;
}
#Override
public void onMapReady(GoogleMap map) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(-18.142, 178.431), 2));
// Polylines are useful for marking paths and routes on the map.
map.addPolyline(new PolylineOptions().geodesic(true)
.add(new LatLng(-33.866, 151.195)) // Sydney
.add(new LatLng(-18.142, 178.431)) // Fiji
.add(new LatLng(21.291, -157.821)) // Hawaii
.add(new LatLng(37.423, -122.091)) // Mountain View
);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
initializeMap();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}

google map tiles load only after taking an action

I am having a small issue when starting my app. The tiles which should show up are only loaded after tapping on the map... afterwards all seems to work fine!
In logcat I see the following error:
E/EnterpriseContainerManager﹕ ContainerPolicy Service is not yet
ready!!!
public class MainActivity extends FragmentActivity {
private static final String TAG = "MAIN_ACTIVITY";
private MyLocationListener locListener;
private SupportMapFragment supportMapFragment;
private GoogleMap gmap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setUpMap();
list = new ArrayList<GPSCoordinates>();
new Object();
}
#Override
protected void onStart() {
super.onStart();
if (gmap == null) {
gmap = supportMapFragment.getMap();
Log.i(TAG, "gmap set!");
}
if(locListener == null) {
this.initLocationManager();
}
Log.i(TAG, "gmap start!");
}
#Override
protected void onStop() {
super.onStop();
Log.i(TAG, "gmap stop!");
}
private void setUpMap() {
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_NORMAL)
.camera(CameraPosition.fromLatLngZoom(new LatLng(47.384906, 15.093149), 25));
//supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
if(supportMapFragment == null) {
supportMapFragment = SupportMapFragment.newInstance(options);
getSupportFragmentManager().beginTransaction().replace(R.id.map, supportMapFragment).commit();
}
}
}
<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="at.ac.unileoben.infotech.paapp.MainActivity"
tools:ignore="MissingPrefix">
<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.SupportMapFragment" />
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="at.ac.unileoben.infotech.paapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="at.ac.unileoben.infotech.paapp.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="at.ac.unileoben.infotech.paapp.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="at.ac.unileoben.infotech.paapp.MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="at.ac.unileoben.infotech.paapp.SettingsActivity"
android:label="#string/action_settings" />
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="XXX" />
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version"/>
</application>
</manifest>
edit:
i changed the code of my main_activity to the following..
public class MainActivity extends FragmentActivity {
private ArrayList<GPSCoordinates> list;
private static final String TAG = "MAIN_ACTIVITY";
private static Context context;
private MyLocationListener locListener;
private SupportMapFragment supportMapFragment;
private GoogleMap gmap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setUpMap();
list = new ArrayList<GPSCoordinates>();
// access context global
MainActivity.context = getApplicationContext();
new Object();
}
#Override
protected void onStart() {
super.onStart();
if (gmap == null) {
gmap = supportMapFragment.getMap();
Log.i(TAG, "gmap set!");
}
if(locListener == null) {
this.initLocationManager();
}
Log.i(TAG, "gmap start!");
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "gmap resume!");
}
private void setUpMap() {
if(supportMapFragment == null) {
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
}
}
later on im calling my simulatelocationmanager with:
private void initLocationManager() {
locListener = new MyLocationListener(gmap);
// Define a listener that responds to location updates
// Register the listener with the Location Manager to receive location updates
SimulateLocationManager simulatedLocationManager = new SimulateLocationManager();
//LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
simulatedLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 0, locListener);
Log.i(TAG, "locListener");
}
in the locationmanager i call the function viewlocation onlocationchanged
public void viewLocation(double latitude, double longitude)
{
float bearing = this.bearing();
Log.i(TAG2, "bearing" + bearing);
gmap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.bearing(bearing)
.tilt(55f)
.zoom(gmap.getCameraPosition().zoom).build()));
}
as i allready said before the problem is that the tiles arent shown till i tap on the map..
all the other things seem to work because i can see the camera moving. but why are the tiles not loaded?
thank you for your reply!
Already accepted answer is there about your issue :Find here
If you set up the SupportMapFragment via the <fragment> element in the layout, you can call getMap() successfully in onCreate(). But, if you create the SupportMapFragment via the constructor, that's too soon -- the GoogleMap does not yet exist. You can extend SupportMapFragment and override onActivityCreated(), as getMap() is ready by then.
However, getMap() can also return null for a bigger problem, such as Google Play Services not being installed. You would need to use something like GooglePlayServicesUtil.isGooglePlayServicesAvailable() to detect this condition and deal with it however you wish.

google maps v2 center mylocation

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

Android Maps API: Failed resolving interface

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...

Android google maps does not appear

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 .

Categories

Resources