Why am I getting a white screen instead of map? - android

Here is the code. I'm getting latitude and longitude in textview above the screen. googel symbols appears. but map dont appear instead a white screen appears. And i feel in this code network provider is used instead of internet provider. which is good to get a map where ever.?
MApActivity
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MapActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
Toast.makeText(getBaseContext(),"No service", Toast.LENGTH_SHORT).show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.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
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#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
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
}
Manifest.xml
I addded all the requirements correctly I guess.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abhayatma"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<permission
android:name="com.example.xxxx.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.xxxx.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<android:uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
<android:uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
----------------
------------
<activity
android:name=".MapActivity"
android:label="#string/title_activity_map" >
</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="AIzaSyBv0UVaXXYiFGWBdNb_DNSQIdkI9672IlY" />
<uses-library android:name="com.google.android.maps" />
</application>
</manifest>

Please check these permission in manifest
<permission
android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your api key of gooogle console" />

Related

How to find distance and travel route from current location to set marker

I am doing project on taxi fare calculation, my current location is displayed but i want to calculate distance and also show travel route from current location to other city using latitude..
please suggest n help...
Maps.java
package com.example.mainproject;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.example.mainproject.R;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Maps extends FragmentActivity implements LocationListener {
// Google Map
private GoogleMap googleMap;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
try {
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(false);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME,
MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and
LocationManager.PASSIVE_PROVIDER
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
googleMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onProviderDisabled(String provider) { }
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
/**
* function to load map If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager().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();
}
}
}
}
map.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mainproject"
android:versionCode="1"
android:versionName="1.0" >
<permission
android:name="com.example.mainproject.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.mainproject.permission.MAPS_RECEIVE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Required OpenGL ES 2.0. for Maps V2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!-- Requires OpenGL ES version 2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<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.example.mainproject.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 class=".selectcity" android:label="selectcity"
android:name="com.example.mainproject.selectcity">
</activity>
<activity class=".About" android:label="About"
android:name="com.example.mainproject.About">
</activity>
<activity class=".entervalues" android:label="entervalues"
android:name="com.example.mainproject.entervalues">
</activity>
<activity class=".exit" android:label="exit" android:name="com.example.mainproject.exit">
</activity>
<activity class=".Maps" android:label="Maps" android:name="com.example.mainproject.Maps">
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIza***************`enter code here`"/>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
For getting direction and distance from Google you have to do following:
Write this code on direction button's click listener or anywhere from that you want to show direction and distance.
String uri = "http://maps.google.com/maps?saddr="
+ source_latitude + "," + source_longitude + "&daddr="
+ destination_latitude + ","
+ destination_longitude;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(intent);

Google map won't display on android realdevice(2.3) but display on emulator

I develop an android application for tracking Nearest ATMs.Map was displayed on Android emulator 2.3.3(API 10) and android 4.3(API 18). And in Emulator the user current location not displayed. The Target of emulators are not Google APIs. But map not Displayed on real device android 2.3.6 (Gingerbread). How to install App to real device? just copy to SD card and install is enough for this app? so please help me.Thanks in advance.
My Files:
MainActivity.java
package com.example.atmtracker;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.CancelableCallback;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends android.support.v4.app.FragmentActivity implements LocationListener{
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
private GoogleMap map;
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private LocationManager locationmanager;
private String provider;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
{
initailizemap();
}
catch(Exception e)
{
e.printStackTrace();
}
}
#SuppressLint("ShowToast")
private void initailizemap() {
// TODO Auto-generated method stub
if(map==null)
{
map=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if(map==null)
{
Toast.makeText(getApplicationContext(), "don't display map", Toast.LENGTH_LONG).show();
}
else
{
map.setMyLocationEnabled(true);
map.setMapType(map.MAP_TYPE_NORMAL);
map.getUiSettings().setMyLocationButtonEnabled(true);
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG,15));
Criteria criteria = new Criteria();
locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
// Getting the name of the best provider
String provider = locationmanager.getBestProvider(criteria, true);
// Getting Current Location
try
{
Location location = locationmanager.getLastKnownLocation(provider);
if(location!=null){
// Getting latitude of the current location
Log.i("Loc","GEt location");
double latitude = location.getLatitude();
Log.i("Lat","GEt lat");
// Getting longitude of the current location
double longitude = location.getLongitude();
Log.i("Lng","GEt lang");
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
String loc=String.valueOf(latLng);
Log.i("latlng",loc);
Toast.makeText(getApplicationContext(),loc ,Toast.LENGTH_LONG);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
map.animateCamera(CameraUpdateFactory.zoomTo(10));
LatLng myPosition = new LatLng(latitude, longitude);
map.setTrafficEnabled(true);
map.addMarker(new MarkerOptions().position(myPosition).title("Start").snippet("kvp").icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
}
else
{
Log.i("loc","Location is null");
Toast.makeText(this, "location is null",Toast.LENGTH_LONG);
}
}
catch(Exception e)
{
Log.i("Loc","don't get location");
Toast.makeText(getApplicationContext(), "don't get Location", Toast.LENGTH_LONG);
}
}
}
}
protected void onResume()
{
super.onResume();
initailizemap();
}
#Override
public void onLocationChanged(Location arg0)
{
// TODO Auto-generated method stub
Location location = locationmanager.getLastKnownLocation(provider);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationmanager.removeUpdates(this);
}
#Override
public void onProviderDisabled(String arg0)
{
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0)
{
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{
// TODO Auto-generated method stub
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.atmtracker"
android:versionCode="1"
android:versionName="1.0"
>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBTjnSiMMWGtQAYln6NUNMHjFQ4l5AWrzA"/>
<permission
android:name="com.example.atmtracker.permission.MAPS_RECEIVE"
android:protectionLevel="signature"
/>
<uses-permission android:name="com.example.atmtracker.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission" />
<!-- show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00010000"
android:required="true"/>
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.atmtracker.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="API_KEY_VALUE"/>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
activitymian.xml::
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
logcat errors:
Failed to find provider info for com.google.android.gsf.gservices
correct Code:
After I changed This code i got map on My device.
No need to put API_key in 2 places. just place it APPLICATION tag.
when Release the app to public remove " android:debuggable="true" " line from manifest file.
use com.google.android.providers.gsf.permission.READ_GSERVICES permission instead of com.google.android.providers.gsf.permission in manifest file.
No change in Main Activity
some changes in manifest file
<permission
android:name="com.example.atmtracker.permission.MAPS_RECEIVE"
android:protectionLevel="signature"
/>
<uses-permission android:name="com.example.atmtracker.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- show current location -->
<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"/>
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.atmtracker.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="API_KEY"/>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>

current location is not loading at Startup

when i run the application it load the map but not my current location.when i clicked on gps after then it zoom in to my current location. i also want to update the location as the user moves from one location to another. this location update code is not working properly. And when i change the orientation of device it reload the map again.Same things happens again.
Xml file
<?xml version="1.0" encoding="utf-8"?>
<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"/>
class file
package com.design.googlemap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity{
private GoogleMap googlemap;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetMapIfNeeded();
}
private void SetMapIfNeeded() {
// TODO Auto-generated method stub
if(googlemap==null){
//try to obtain google map form SupportMapFragment;
googlemap=((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if(googlemap!= null){
SetUpMap();
}
}
}
private void SetUpMap() {
// Enable MyLocation Layer of Google Map
googlemap.setMyLocationEnabled(true);
// Get LocationManager object from System Service Location_SERVICE
locationManager =(LocationManager) getSystemService(LOCATION_SERVICE);
//Create a criteria object to retrieve provider
Criteria criteria= new Criteria();
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria,true);
//Get Current Location
Location myLocation= locationManager.getLastKnownLocation(provider);
//Set map type
googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Get Latitude object of current location
double latitude=myLocation.getLatitude();
//Get Latitude object of current location
double longitude=myLocation.getLatitude();
//Create a LatLng object for current location
LatLng latLng = new LatLng(latitude,longitude);
//show the current location of Google Map
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
LocationListener listner = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locationManager =(LocationManager) getSystemService(LOCATION_SERVICE);
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) listner);
}
#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;
}
}
ManifestFile
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.design.googlemap"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="17" />
<permission
android:name="com.design.googlemap.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<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" />
<uses-permission android:name="com.design.googlemap.permission.MAPS_RECEIVE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.design.googlemap.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="XXXXXXXXXXXXXXXXXXXXXXXXXXXX" />
</application>
</manifest>
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria,false);
Even if Gps if Off. Your approx location will be pointed.
And for locationUpdates on your GoogleMaps go through this link
Also for zooming to a particular position add this code:
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(YOUR_LATLNG).zoom(ZOOM_LEVEL).build(); // int ZOOM_LEVEL=12
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
go through this link for more on zooming.
To hide the WebView call the Visibility functions in your Activity[OnClick of your Button]
WebView wv=(WebView)findViewById(R.id.YOUR_WEB_VIEW);
wv.setVisibility(View.GONE);// when you want to hide[shrink]
wv.setVisibility(View.VISIBLE);// when you want to Show[Zoom]
1. If you only want to show your own location, than a MyLocationOverlay is probably easiest.
Quick information here (rest of that article might be helpful too):
http://www.vogella.com/articles/AndroidLocationAPI/article.html#maps_mylocation
Use MyLocationOverlay, as that is what it is there for. Here is a sample application that uses MyLocationOverlay and a custom overlay; you can always get rid of the custom one if you do not need it.
2. To avoid the common behavior of reloading, you have to handle configuration change for your app .
Add this line to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.
android:configChanges="keyboardHidden|orientation|screenSize"

Google Maps V2 Not Woking

I m using google maps v2 and getting this error.
Could not find class 'maps.af.k', referenced from method maps.ag.an.a
I m following all the rules correctly. I have created SHA1 finger print and added it to ANdroid Key for apikey with projct name
1F:41:29:EC:E8:07:3C:A9:F8:6E:EB:D2:7B:42:41:62:3A:36:CA:F2;com.example.routes
Then in mainest file i m using
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
i have also imported the googleplayservices and correctly added it to the project
My code is
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment fragment = new SupportMapFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, fragment).commit();
;
googleMap = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
}
}
but still i m getting that error.
Try to extend Activity rather then FragmentActivity:
public class MainActivity extends Activity implements LocationListener{
LocationManager locationManager;
private GoogleMap googleMap;
double lat=17.385044;
double long=78.486671;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service=(LocationManager)getSystemService(LOCATION_SERVICE);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
private void initilizeMap(){
if(googleMap==null){
googleMap=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
//check if map is created succesfully or not
if(googleMap==null){
Toast.makeText(getApplicationContext(),"sorry unable to create map",1).show();
}
}
MarkerOptions markerOptions=new MarkerOptions().position(new LatLng(lat,long));
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
CameraPosition cameraPosition=new CameraPosition.Builder().target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
googleMap.setMyLocationEnabled(true);
googleMap.setOnInfoWindowClickListener(null);
}
#Override
protected void onResume(){
super.onResume();
initilizeMap();
}
I had the same problem and my solution was to remove and add the googleplayservices again.
When you are using SupportMapFragment no need of extending FragmentActivity just extend the Activity See the below example code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
public class MainActivity extends Activity {
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
#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;
}
}
Note: You have to add google play services library project as a reference to your project, your package name must be com.example.routes you have to add the map fragment in your xml layout not in the manifest.
Make following changes to your Manifest.xml
Add following permissions.
<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"/>
Add the OpenGL
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
Add the API key
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY"/>
Example manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.package"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<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"/>
<used-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.package.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOUR_API_KEY_HERE"/>
</application>

android + google map api v2 + current location

i am creating an app with a google map view and i want this app to detect the current location of the user and display the lat and long with a marker on the map but all i can do until now is the display of the google map and the detection of current location without any marker displayed and without any text appear to display the lat and long
i did not add a marker until now because i do not know where to put it in the code and what is the best practice to do that
can anyone help me ???
this is the code of the:
manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.wptrafficanalyzer.locationgooglemapv2demo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<permission
android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="in.wptrafficanalyzer.locationgooglemapv2demo.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="API KEY" />
</application>
</manifest>
xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
java file
package in.wptrafficanalyzer.locationgooglemapv2demo;
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
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 of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.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
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#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
}
#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;
}
}
First check the documentation here, it gives good indication on best strategies for getting user position.
Personally I usually start the map with a marker placed at the position retrivied with
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
and then I start listening for position update and move the marker.
It also depend on how accurate position you need for the pourpose of your application, if you don't need really accurate position but the area is sufficient maybe you can just use thelastKnownLocation.
You can try something like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
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 of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.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
Location location = locationManager.getLastKnownLocation(provider);
LocationListener locationListener = new LocationListener() {
void onLocationChanged(Location location) {
// redraw the marker when get location update.
drawMarker(location);
}
if(location!=null){
//PLACE THE INITIAL MARKER
drawMarker(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
}
}
private void drawMarker(Location location){
// Remove any existing markers on the map
googleMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("ME"));
}
Also you don't need the Activity class to implements LocationListener, you can just define a listener and register it as I did above
P.S. I don't have an editor son my code can contain typo
Hope this helps, cheers
I just had the same problem, and found a way to do it using the Google Maps API:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
No need for LocationService or LocationManager at all.
Full shortcut for defining the Google Map android v2 in android......
XML File :
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Menifest file :
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_MOCK_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.ACCESS_NETWORK_STATE" />
<!-- Map permission Starts -->
<permission
android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!-- Map permission Starts -->
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.mapdemoapiv2.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=".MapDetail" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your Key" />
<uses-library android:name="com.google.android.maps" />
</application>
Activity class :
public class MainActivity extends android.support.v4.app.FragmentActivity
{
GoogleMap googleMap;
MarkerOptions markerOptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
GetCurrentLocation();
}
private void setUpMapIfNeeded() {
if (googleMap == null) {
Log.e("", "Into null map");
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(
MainActivity.this));
if (googleMap != null) {
Log.e("", "Into full map");
googleMap.setMapType(googleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setZoomControlsEnabled(false);
}
}
}
private void GetCurrentLocation() {
double[] d = getlocation();
Share.lat = d[0];
Share.lng = d[1];
googleMap
.addMarker(new MarkerOptions()
.position(new LatLng(Share.lat, Share.lng))
.title("Current Location")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.dot_blue)));
googleMap
.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(Share.lat, Share.lng), 5));
}
public double[] getlocation() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location l = null;
for (int i = 0; i < providers.size(); i++) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
It is better to use:
Location currentLocation =
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
Documentation
easy like that:
after this -
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your Key" />
put this -
<meta-data android:name="com.google.android.gms.version" android:value="4030500" />

Categories

Resources