Issue: ProjectManager.getInstance(); gives null object, I am clueless I have done the code as below,
Activity class & Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="proj.Mobi">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:hardwareAccelerated="true"
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>
<meta-data android:name="com.here.android.maps.appid" android:value="WcIOjXKhgYk8" />
<meta-data android:name="com.here.android.maps.apptoken" android:value="XaRs1SILAVi2sw" />
<meta-data android:name="com.here.android.maps.license.key" android:value="phEpi5ZL3jiNTElgM3ldzrJTeevoNeYY47oE9eSzgJfySv=" />
</application>
</manifest>
I am creating class of map activity below, I have created the PositioningManager.getInstance() it gives null object by Toast popup
public class MainActivity extends AppCompatActivity {
// map embedded in the map fragment
private Map map = null;
// map fragment embedded in this activity
private MapFragment mapFragment = null;
private PositioningManager positioningManager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Positioning Manager
positioningManager = PositioningManager.getInstance();
if (positioningManager == null) {
Toast.makeText(MainActivity.this, " Positioning Null", Toast.LENGTH_LONG).show();
}
// Search for the map fragment to finish setup by calling init().
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapfragment);
mapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(
OnEngineInitListener.Error error) {
if (error == OnEngineInitListener.Error.NONE) {
// retrieve a reference of the map from the map fragment
map = mapFragment.getMap();
// Set the map center to the Vancouver region (no animation)
map.setCenter(new GeoCoordinate(12.9172, 77.5738, 0.0),
Map.Animation.NONE);
// Set the zoom level to the average between min and max
map.setZoomLevel(
(map.getMaxZoomLevel() + map.getMinZoomLevel()) / 2);
} else {
System.out.println("ERROR: Cannot initialize Map Fragment");
Toast.makeText(MainActivity.this, "Error:" + error.toString(), Toast.LENGTH_LONG).show();
}
}
});
}
}
Everything that's HERE Maps related needs to happen after initialization. This is applicable for everything related to the HERE MobileSDK.
Try getting the PositioningManager inside your EngineInitListener.onEngineInitializationCompleted (and keep in mind, once you get the instance, you also have to call start on it to receive any events)
Related
I am building navigation app using HERE-Maps and this Github example, I replicated most of the code, I created new credentials for my app and followed steps written in documentation. But my code is crashing on EngineInitializationCompleted I think its because of some mistake I did in Manifest, Regarding Map Service or Disk cache.
I am getting this error below:
03-28 13:16:21.077 26352-26352/propelit.actionopps.com.propelit D/xxxxxx: Unknown error occurred.
java.lang.SecurityException: Not allowed to start service Intent { act={YOUR_INTENT_NAME} cmp=com.here.android.example.basicpositioningsolution/com.here.android.mpa.service.MapService (has extras) } without permission not exported from uid 10205
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1418)
at android.app.ContextImpl.startService(ContextImpl.java:1395)
at android.content.ContextWrapper.startService(ContextWrapper.java:623)
at com.nokia.maps.MapServiceClient.a(MapServiceClient.java:77)
at com.nokia.maps.MapsEngine.a(MapsEngine.java:621)
at com.nokia.maps.MapsEngine.a(MapsEngine.java:363)
at com.here.android.mpa.common.MapEngine.init(MapEngine.java:261)
at com.nokia.maps.bw.a(MapFragmentImpl.java:132)
at com.here.android.mpa.mapping.MapFragment.init(MapFragment.java:112)
at propelit.actionopps.com.propelit.MainActivity.initializeMapsAndPositioning(MainActivity.java:178)
at propelit.actionopps.com.propelit.MainActivity.onRequestPermissionsResult(MainActivity.java:369)
at propelit.actionopps.com.propelit.MainActivity.checkPermissions(MainActivity.java:350)
at propelit.actionopps.com.propelit.MainActivity.onCreate(MainActivity.java:79)
at android.app.Activity.performCreate(Activity.java:6852)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
My Manifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="propelit.actionopps.com.propelit">
<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.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:maxSdkVersion="22" android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:screenOrientation="portrait"
android:theme="#style/AppTheme"
android:label="#string/app_name" android:hardwareAccelerated="true">
<meta-data android:name="com.here.android.maps.appid" android:value="skxxxxxxxxxxxxxxxxZO"/>
<meta-data android:name="com.here.android.maps.apptoken" android:value="Dgm_cxxxxxxxxxxxxxxv6FGEeQ"/>
<meta-data android:name="com.here.android.maps.license.key" android:value="hZxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxZuC0m2vtXunxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5wZVsq1Li2RSU="/>
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
</activity>
<activity
android:name=".SplashScreen"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:screenOrientation="portrait"
android:name=".LoginActivity"
android:label="#string/title_activity_login"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
</activity>
<meta-data
android:name="INTENT_NAME"
android:value="{YOUR_INTENT_NAME}" />
<service
android:name="com.here.android.mpa.service.MapService"
android:label="{YOUR_LABEL_NAME}"
android:exported="false">
<intent-filter>
<action android:name="{YOUR_INTENT_NAME}">
</action>
</intent-filter>
</service>
<!--
Embed the HERE Positioning Service.
For more information, see the HERE SDK Developer's Guide
-->
<service android:enabled="true" android:exported="false" android:name="com.here.services.internal.LocationService" android:process=":remote">
</service>
</application>
</manifest>
My MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
checkPermissions();
private void initializeMapsAndPositioning() {
setContentView(R.layout.activity_main);
mTopToolbar = (Toolbar) findViewById(R.id.toolbar);
rotateLoading = (RotateLoading) findViewById(R.id.progressBar2);
setSupportActionBar(mTopToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
navigationView.setNavigationItemSelectedListener(this);
}
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawer, mTopToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawer.addDrawerListener(toggle);
toggle.syncState();
Window window = this.getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(ContextCompat.getColor(this ,R.color.colorPrimaryDark));
}
mLocationInfo = (TextView) findViewById(R.id.textViewLocationInfo);
mapFragment = (MapFragment)getFragmentManager().findFragmentById(
R.id.mapfragment);
mapFragment.setRetainInstance(false);
// Set path of isolated disk cache
String diskCacheRoot = Environment.getExternalStorageDirectory().getPath()
+ File.separator + ".isolated-here-maps";
// Retrieve intent name from manifest
String intentName = "";
try {
ApplicationInfo ai = getPackageManager().getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
intentName = bundle.getString("INTENT_NAME");
} catch (PackageManager.NameNotFoundException e) {
Log.e(this.getClass().toString(), "Failed to find intent name, NameNotFound: " + e.getMessage());
}
Toast.makeText(MainActivity.this, "before", Toast.LENGTH_SHORT).show();
boolean success = MapSettings.setIsolatedDiskCacheRootPath(diskCacheRoot, intentName);
if (!success) {
Toast.makeText(MainActivity.this, "diskcache", Toast.LENGTH_SHORT).show();
// Setting the isolated disk cache was not successful, please check if the path is valid and
// ensure that it does not match the default location
// (getExternalStorageDirectory()/.here-maps).
// Also, ensure the provided intent name does not match the default intent name.
} else {
mapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(Error error) {
Toast.makeText(MainActivity.this, "inside", Toast.LENGTH_SHORT).show();
if (error == Error.NONE) {
Toast.makeText(MainActivity.this, "inside 2", Toast.LENGTH_SHORT).show();
map = mapFragment.getMap();
map.setCenter(new GeoCoordinate(61.497961, 23.763606, 0.0), Map.Animation.NONE);
map.setZoomLevel(map.getMaxZoomLevel() - 1);
map.addTransformListener(MainActivity.this);
mPositioningManager = PositioningManager.getInstance();
mHereLocation = LocationDataSourceHERE.getInstance(
new StatusListener() {
#Override
public void onOfflineModeChanged(boolean offline) {
// called when offline mode changes
}
#Override
public void onAirplaneModeEnabled() {
// called when airplane mode is enabled
}
#Override
public void onWifiScansDisabled() {
// called when Wi-Fi scans are disabled
}
#Override
public void onBluetoothDisabled() {
// called when Bluetooth is disabled
}
#Override
public void onCellDisabled() {
// called when Cell radios are switch off
}
#Override
public void onGnssLocationDisabled() {
// called when GPS positioning is disabled
}
#Override
public void onNetworkLocationDisabled() {
// called when network positioning is disabled
}
#Override
public void onServiceError(ServiceError serviceError) {
// called on HERE service error
}
#Override
public void onPositioningError(PositioningError positioningError) {
// called when positioning fails
}
});
if (mHereLocation == null) {
Toast.makeText(MainActivity.this, "LocationDataSourceHERE.getInstance(): failed, exiting", Toast.LENGTH_LONG).show();
finish();
}
mPositioningManager.setDataSource(mHereLocation);
mPositioningManager.addListener(new WeakReference<PositioningManager.OnPositionChangedListener>(
MainActivity.this));
// start position updates, accepting GPS, network or indoor positions
if (mPositioningManager.start(PositioningManager.LocationMethod.GPS_NETWORK_INDOOR)) {
mapFragment.getPositionIndicator().setVisible(true);
} else {
Toast.makeText(MainActivity.this, "PositioningManager.start: failed, exiting", Toast.LENGTH_LONG).show();
finish();
}
} else {
Log.d("xxxxxx", error.getDetails());
Log.d("xxxxxx", error.getStackTrace());
Toast.makeText(MainActivity.this, "onEngineInitializationCompleted: error: " + error + ", exiting", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
}
// some more overriden methods and callback methods
<meta-data
android:name="INTENT_NAME"
android:value="{YOUR_INTENT_NAME}" />
<service
android:name="com.here.android.mpa.service.MapService"
android:label="{YOUR_LABEL_NAME}"
android:exported="false">
<intent-filter>
<action android:name="{YOUR_INTENT_NAME}">
</action>
</intent-filter>
</service>
Put your service name here
android:label="{YOUR_LABEL_NAME}"
android:value="{YOUR_INTENT_NAME}"
action android:name="{YOUR_INTENT_NAME}"
fill these places properly, you didn't mention activity and service names
I am new to HERE maps currently trying to get current user location from Positioning manager , getlocation() method, but my code always return below information
com.nokia.maps.GeoPositionImpl[coordinate=GeoCoordinate [Latitude=-179769313486232000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000 Longitude=-179769313486232000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000 Altitude=1073741824.000000 Valid=FALSE]]
Below is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//requestPermissions();
// Search for the Map Fragment
final MapFragment mapFragment = (MapFragment)
getFragmentManager().findFragmentById(R.id.mapfragment);
// initialize the Map Fragment and
// retrieve the map that is associated to the fragment
mapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(
OnEngineInitListener.Error error) {
if (error == OnEngineInitListener.Error.NONE) {
// now the map is ready to be used
map = mapFragment.getMap();
onMapFragmentInitializationCompleted();
} else {
System.out.println("ERROR: Cannot initialize MapFragment");
System.out.println("ERROR: Cannot initialize Map Fragment: " + error.toString());
}
}
});
}
private void onMapFragmentInitializationCompleted() {
PositioningManager posManager;
MapContainer placesContainer = null;
// retrieve a reference of the map from the map fragment
// map = mapFragment.getMap();
// start the position manager
posManager = PositioningManager.getInstance();
posManager.start(PositioningManager.LocationMethod.GPS_NETWORK);
GeoPosition position = posManager.getPosition();
GeoCoordinate cor = position.getCoordinate();
// Set a pedestrian friendly map scheme
map.setMapScheme(Map.Scheme.PEDESTRIAN_DAY);
// Display position indicator
map.getPositionIndicator().setVisible(true);
placesContainer = new MapContainer();
map.addMapObject(placesContainer);
// Set the map center coordinate to the current position
map.setCenter(posManager.getPosition().getCoordinate(), Map.Animation.NONE);
map.setZoomLevel(14);
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.benz.event.navigation">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="navigation"
android:hardwareAccelerated="true"
android:roundIcon="#mipmap/ic_launcher_round"
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>
<meta-data android:name="com.here.android.maps.appid" android:value="MY ID"/>
<meta-data android:name="com.here.android.maps.apptoken" android:value="MY TOKEN"/>
<meta-data android:name="com.here.android.maps.license.key" android:value="MY KEY"/>
<!--
Embed the HERE Map Service.
For more information, see the HERE SDK Developer's Guide
-->
<service
android:name="com.here.android.mpa.service.MapService"
android:label="HereMapService"
android:process="global.Here.Map.Service.v2"
android:exported="true" >
<intent-filter>
<action android:name="com.here.android.mpa.service.MapService" >
</action>
</intent-filter>
</service>
</application>
</manifest>
Any help/hint will save my day
Thanks
Valid=FALSE Implies your device does not have a GPS lock. Is your device indoors and unable to obtain a position? Second, please check to see if your application has the positioning permission.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION " />
I am trying to build a location based MAP app and when I try to execute my App, I can view my Markers added to the Mapsactivity, however i don't Map on the activity
I can confirm that I have provide the correct Map key for my activity getting the key from console.developer.com and enabling Google Maps for Android API
Please suggest what could be wrong here
MapsActivity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private final String TAG = "MapActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Log.d(TAG, "inside create Fragment");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Log.d(TAG, "outside create Fragment");
}
#Override
public void onMapReady(GoogleMap map) {
SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Double mLat = Double.parseDouble(preferences.getString("latitude",""));
Double mLon = Double.parseDouble(preferences.getString("longtitude",""));
Log.d(TAG, preferences.getString("latitude",""));
Log.d(TAG, preferences.getString("longtitude",""));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLat,mLon), 20));
map.addMarker(new MarkerOptions().position(new LatLng(mLat,mLon)));
//map.setMyLocationEnabled(true);
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<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.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<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>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity android:name=".MyGames"/>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key"/>
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.android.wesport.MainActivity"/>
</activity>
</application>
Activity_maps.xml
<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="match_parent"
tools:context=".MapsActivity"/>
Image from the emulator
Probably you show desert on the map.
Try change:
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLat,mLon), 20));
to
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLat, mLon), 5));
I am doing a simple app that has to do with maps in Android studio. When I run it with the release key,
keytool -list -v -keystore C:\Users\Theodosios\maps.jks -alias mapsalias -storepass
larissa -keypass larissa
the map doesn't run correctly. If I use the debug.kestore though everything works fine.The message in the output is
01-06 00:17:00.904: E/ActivityThread(1665):
Service com.google.android.gms.backup.BackupTransportService has leaked
ServiceConnection com.google.android.gms.http.f#3c9e1e50
that was originally bound here.
01-06 00:17:00.904: E/ActivityThread(1665):
android.app.ServiceConnectionLeaked: Service
com.google.android.gms.backup.BackupTransportService has leaked ServiceConnection
com.google.android.gms.http.f#3c9e1e50
that was originally bound here
01-06 00:17:00.904: E/ActivityThread(1665): at
android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:966)
01-06 00:17:00.904:
E/ActivityThread(1665):
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1768)
I took the code code of the MainActivity from google.It's pretty straight forward.
public class MainActivity extends ActionBarActivity {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createMapView();
addMarker();
}
/**
* Initialises the mapview
*/
private void createMapView(){
/**
* Catch the null pointer exception that
* may be thrown when initialising the map
*/
try {
if(null == googleMap){
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.mapView)).getMap();
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if(null == googleMap) {
Toast.makeText(getApplicationContext(),
"Error creating map", Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception){
Log.e("mapApp", exception.toString());
}
}
private void addMarker(){
/** Make sure that the map has been initialised **/
if(null != googleMap){
Marker marker1= googleMap.addMarker(new MarkerOptions()
.position(new LatLng(39.648141,22.413155))
.title("Marker")
.draggable(true)
);
}
}
}
In the manifest file I add the necessary permissions.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="map.example.com.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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="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=".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.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="MY KEY FROM GOOLE API CONSOLE GOES HERE" />
</application>
</manifest>
I want to run demo Google map but it is not showing map. Here is my code.I have checked API key it is correct
package com.example.googlemaps;
import com.google.android.maps.MapActivity;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends MapActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return true;
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googlemaps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"/>
<uses-permission android:name="android.permission.INTERNET" />
<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.androidhive.googlemaps.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>
layout xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey="#string/Api_key"
/>
This is old way for getting map. Google has updated it now.
use
<fragment
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
in your xml layout.
provide your API key in manifest file as
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOUR-API-KEY" />
in your application tag.
also don't extend MapActivity. Instead extend normal Activity
then write below code in your OnCreate
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
// Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
// Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// Getting Google Map
myMap = fragment.getMap();
// Enabling MyLocation in Google Map
myMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service
// LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
also add following code on OnResume
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
that's it.
All the best!
Version 1 googlemaps officially depricated.so just use version 2 and add google-play-services libs.surely it will help to get googlemap.
public class MainActivity extends FragmentActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap(); } }
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE"
/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.vogella.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="AIzaSyDeYchyvOUsy_I68_RMtfsI5QVkqweIp9w" />
</application>
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
refer this link,http://www.vogella.com/articles/AndroidGoogleMaps/article.html