google map given error unfortunatley googlemap has stopped - android

I am design a Google map in android , I have add Google map service lib,layout
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
/>
Main Activity is
public class MainActivity extends Activity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
Marker ciu = mMap.addMarker(new MarkerOptions().position(CIU).title("My Office"));
}
}
Manifest.xml
<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"/>
<permission
android:name="maping.amit.com.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="maping.amit.com.permission.MAPS_RECEIVE"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="my keys are there ....."/>

Providing the link follow where you can get the map
and for marking your location you this code
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_marker_icon)));
// adding marker
googleMap.addMarker(marker);

Related

getMap() is null in SupportMapFragment in google map in android fragment

I am using google map in a fragment and getting null when calling getMap(), this is my code:
In my MapViewFragment
private GoogleMap mGoogleMap;
I am getting null at this line, in onCreate() method...
mGoogleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
In fragment_map_view file
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
The getMap method is deprecated. You should use getMapAsync:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mGoogleMap = googleMap;
// Do something with your map
}
}
did you add the permissions and google API key ?
here is my code from project call this function in OnCreate()
private void CheckGoogleMap()
{
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
catch (Exception e) {
e.printStackTrace();
}
}
in XML file
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
in Manifest file
<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.example.googlemaps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET"/>
<permission android:name="com.example.googlemaps.permission.MAPS_RECEIVE" />
<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" />
before closing of application TAG in Manifest file add this
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOUR API KEY" />
in Gradle add
compile 'com.google.android.gms:play-services:8.1.0'
I got the reason for it, I think I should post for future readers......
Actually as I GoogleMap was called in a fragment so, in the line..
mGoogleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
instead of
getFragmentManager(), getSupportFragmentManager() should be used in fragments.
Corrected one-
mGoogleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

Google map not coming despite no errors

I am trying to load google map in emulator for a given latitude and longitude.
Map is loading in the emulator but no marker is coming and same view is shown always.
i have followed the tutorial. Below is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
double latitude = getIntent().getDoubleExtra("lat", 0);
double longitude = getIntent().getDoubleExtra("lng", 0);
Log.d("Zumbare","lat value : "+latitude);
Log.d("Zumbare","lng value : "+longitude);
LatLng position = new LatLng(latitude, longitude);
MarkerOptions options = new MarkerOptions();
options.position(position);
options.title("Position");
options.snippet("Latitude:"+latitude+",Longitude:"+longitude);
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.addMarker(options);
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
googleMap.moveCamera(updatePosition);
googleMap.animateCamera(updateZoom);
}
Below is my manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.maptest.gmap" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.app.maptest.gmap.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.app.maptest.gmap.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="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCInpkx8MO-lD4AMR4aUYns3tVvUMjIH1k" />
<activity
android:name=".MainActivity2"
android:label="#string/title_activity_main_activity2" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can someone help me where the problem is..
Edit :
Yes, I am fetching lat lng of a city and logs are coming as..
1885-1885/com.app.maptest.gmap D/Zumbareļ¹• lat value : 16.506174
03-29 16:20:54.602 1885-1885/com.app.maptest.gmap D/Zumbareļ¹• lng value : 80.648015
Edit2:
I am using android studio and added the google play service in gradle file as below.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:3.1.36'
}
I think the tutorial that you followed is outdated. play-services now is 6.5.87.
Please try to follow this step by step, you will finally get a map on your phone.
MainAcitivity, sample code:
public class MainActivity extends Activity {
private static LatLng goodLatLng = new LatLng(37, -120);
private GoogleMap googleMap;
private EditText et_address, et_finalAddress;
LatLng addressPos, finalAddressPos;
Marker addressMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_address = (EditText) findViewById(R.id.addressEditText);
et_finalAddress = (EditText) findViewById(R.id.finalAddressEditText);
// Initial Map
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Put a dot on my current location
googleMap.setMyLocationEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setTrafficEnabled(true);
// 3D building
googleMap.setBuildingsEnabled(true);
// Get zoom button
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(goodLatLng)
.title("Hello"));
}
For more details, please refer to my github here.

Map activity in android

I have created map actvity.But its not showing map on mapview.just showing blank blocks.
is there any solution?
activity_main.xml-
<?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.MapFragment"/>
activity code-
package com.example.googlemap;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
manifest file-
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<permission
android:name="com.example.googlemap.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<meta-data
android:name="com.google.android.maps.v2.AIzaSyDRv4Ul_9iPW-roHIsc8EuxKwkRN8jWivs"
android:value="AIzaSyDRv4Ul_9iPW-roHIsc8EuxKwkRN8jWivs" />
<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-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.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>
<uses-library android:name="com.google.android.maps" />
</application>
after using this
i'm getting following exception-
08-22 23:19:52.204: E/AndroidRuntime(584): FATAL EXCEPTION: main
08-22 23:19:52.204: E/AndroidRuntime(584): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.googlemap/com.example.googlemap.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
Old MapView has been depreciated. You can't create a new Map key for publishing your app.
You have to use new Google Maps for Android v2 API. Here's a link to the documents and example.
https://developers.google.com/maps/documentation/android/start
make sure Google Repository && Google play Services is up to Date
add below to Project level Gradle
classpath 'com.google.gms:google-services:3.0.0'
and below two statements to App Level Gradle
compile 'com.google.android.gms:play-services-location:11.0.1'//for location
compile 'com.google.android.gms:play-services-maps:11.0.1'//for maps
compile 'com.google.android.gms:play-services-places:11.0.1'//for places
And add permission in Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
add below statment in tag
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_map_key" />
MapsActivity.class
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.OnConnectionFailedListener {
private Context mContext;
private EditText searchPlaceEt;
private Button saveLocationBtn;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_map);
mContext = MapsActivity.this;
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
if(mMap != null)
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
///checkLocationPermission();
}
} else {
buildGoogleApiClient();
if(mMap != null)
mMap.setMyLocationEnabled(true);
}
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
googleMap.addMarker(new MarkerOptions().
position(mMap.getCameraPosition().target).title("Near to Sydney"));
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Add a hazard here.");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mMap.addMarker(markerOptions);
///mHazardsMarker = mMap.addMarker(markerOptions);
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
LatLng objLoc = marker.getPosition();
return false;
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
LatLng objLoc = marker.getPosition();
}
});
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}
#Override
public void onMarkerDragEnd(Marker marker) {
marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
fragment_map
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".maptest.MapsActivity">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
I could do this with the Google Map Activity bundled with Android Studio 1.2.1.1. I created a Google Maps Activity and followed the instructions as below:
Created the API Key following the instructions in google_maps_api.xml
To get one, follow this link, follow the directions and press "Create" at the end:
https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY%3Bnpackagename
You can also add your credentials to an existing key, using this line:
XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY:XY;newmapscreen.avapps.nbapl.com.newmapscreen
Once you have your key (it starts with "AIza"), replace the "google_maps_key"
string in this file.
-->
<string name="google_maps_key" translatable="false" templateMergeStrategy="preserve">
AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
</string>
After that, I ensured all the dependencies are there in Android Manifest, build.gradle. See this answer for details.
In your MapActivity.java, you can add additional markers, and use the Android Google Maps API V2 features to enhance your map.
(replace XY:XY ...with whats in your google_maps_api.xml)

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" />

How update user's current location in google map

Hi Friends
I want to display user's current location in Google map and add marker of his location in the map and how can i Update their location in google map after every second ..???
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableMyLocation();
myLocationOverlay.runOnFirstFix(addfirststandort);
java file
public class MYGIRNE extends FragmentActivity {
GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygirne);
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
if(map!=null){
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
LocationManager manager=(LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
String provider =manager.getBestProvider(criteria, true);
Location cloc=manager.getLastKnownLocation(provider);
double lat=0;
double lng =0;
lat =cloc.getLatitude();
lng= cloc.getLongitude();
LatLng latlng = new LatLng (lat,lng);
map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
map.addMarker(new MarkerOptions()
.title("Your Current Location")
.position(latlng));
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_AZURE)));
}
}
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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.firsttry.cyptour.MYGIRNE" >
<fragment
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
also include the following in your manifest file
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="enter your APIKEY" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
this code should be an element of application
then include this under the uses permission of your manifest file
<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" />
<!-- External storage for caching. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- My Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Maps API needs OpenGL ES 2.0. -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
i hope this helps

Categories

Resources