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"
Related
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" />
Hi I want the user to be able to find their location on Google Maps v2. Something is happening when I click the location button on the map because a little satellite thing with beams coming off of it appears at the top of my phone. Can anyone help with this problem?
Also as a side question is there any way of adding directions or distance to a defined location too?
MapsActivity.java:
package com.example.softwaresearchapp;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends Activity {
// Google Map
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
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();
}
}
googleMap.setMyLocationEnabled(true); // false to disable
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(52.911927, -1.187923))
.title("Nottingham Trent University - Clifton Campus"));
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);
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.softwaresearchapp"
android:versionCode="1"
android:versionName="1.0" >
<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-sdk android:minSdkVersion="11" android:targetSdkVersion="17" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light">
<activity
android:name="com.example.softwaresearchapp.MainActivity"
android:label="#string/app_name">
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResultsActivity" />
</activity>
<!-- Search results activity -->
<activity android:name="com.example.softwaresearchapp.SearchResultsActivity"
android:parentActivityName="com.example.softwaresearchapp.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<activity android:name ="com.example.softwaresearchapp.MapsActivity"/>
<activity android:name ="com.example.softwaresearchapp.ABActivity"/>
<activity android:name="com.example.softwaresearchapp.SoftwareSearchActivity"/>
<activity android:name="com.example.softwaresearchapp.SplashActivity">
<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="AIzaSyAyPwV_djsaafTUYCjEc_QyUgjnSdnriwg"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
From the docs:
Make a marker draggable
You can reposition a marker once its been added to the map so long as its draggable property is set to true. Long press the marker to enable dragging. When you take your finger off the screen, the marker will remain in that position.
Markers are not draggable by default. You must explicitly set the marker to be draggable either with MarkerOptions.draggable(boolean) prior to adding it to the map, or Marker.setDraggable(boolean) once it has been added to the map. You can listen for drag events on the marker, as described in Marker drag events.
The below snippet adds a draggable marker at Perth, Australia.
static final LatLng PERTH = new LatLng(-31.90, 115.86);
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(PERTH)
.draggable(true));
More info here: https://developers.google.com/maps/documentation/android/marker?hl=nl#make_a_marker_draggable
Check this for the second question: Launching Google Maps Directions via an intent on Android
Here is how to do it:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Also, be sure to add the correct permissions in your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
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>
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" />
Thanks in advance, I'm having dificulties trying to display an icon on my current location in a mobile application using google maps. At the moment I'm able to retrieve the maps from Google maps android api v2 libraries using the using API key etc., and I am able to retrieve my own location on GPS coordinates, "latitude" and "longitude" as they can be displayed on the screen in two textViews in my mobile device. My problem now is how to use those coordinates to display with an icon my own location on the map. Obviously I'm doing something wrong when I try to implement it. I tried to implement it using overlays but I'm having plenty of errors. I don't know why or what way to take.
Here is my code. Any help I would really appreciate it.
thanks
This is my MainActivity.java
package com.example.location3;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
public class MainActivity extends FragmentActivity {
TextView textLat;
TextView textLong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create reference
textLat = (TextView) findViewById(R.id.textLat);
textLong = (TextView) findViewById(R.id.textLong);
// create locationManager object
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// create LocationListener object (listen for changes in the location)
LocationListener ll = new myLocationListener();
// use lm location manager to get update
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
// create a LocationListener to do what we want
class myLocationListener implements LocationListener {
GoogleMap map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// implemented method
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// variables to get and store longitude and latitude
double pLong = location.getLongitude();
double pLat = location.getLatitude();
// set text to display values from longitude and latitude
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
}
}
// implemented method
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
// implemented method
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
// implemented method
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
This is my Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitud"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView3"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textLat"
android:text="Longitud"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
And this is my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.location3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.example.location3.permissions.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.location3.permission.MAP_RECEIVE" />
<!-- to be able to use it for mobiles -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!-- Permision to use Internet to get the maps -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permision for the cache which is done in the external memory -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Permision to use google services -->
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!-- Permision to be able to point in the map where the user is -->
<!-- Permision to use wifi net -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Permision to use GPS -->
<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" >
<uses-library
android:required="true"
android:name="com.google.android.maps" />
<activity
android:name="com.example.location3.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>
<!-- API provided from Google -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCx00iNUdhMi9uyuCO9tTPwX4-nbi4wg6wx" />
</application>
</manifest>
you need to create a class which will handle the overlay wherever you want to pinup on the map. refer this tutorial here
try this :
class CurrentLocationOverlay extends ItemizedOverlay<OverlayItem>{
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
public CurrentLocationOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public CurrentLocationOverlay(Drawable defaultMarker , Context context) {
this(boundCenterBottom(defaultMarker));
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
public void addOverlay(GeoPoint gp , String title , String msg) {
OverlayItem overlay = new OverlayItem(gp, title, msg);
mapOverlays.add(overlay);
this.populate();
}
}
add icon :
Drawable mDrawable = getResources().getDrawable(R.drawable.pinpoint);
GeoPoint point = new GeoPoint((int)(lat* 1E6) , (int)(lng* 1E6));
CurrentLocationOverlay currentLocationOverlay = new CurrentLocationOverlay(mDrawable);
currentLocationOverlay.addOverlay(point ,"" , "");
mapView.getOverlays().add(currentLocationOverlay);