App crashing while implementing current location in android studio - android

home.java
package com.example.nitctraveltogether;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class home extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
GoogleApiClient googleApiClient;
Location lastLocation;
LocationRequest locationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest= new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(locationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
lastLocation= location;
LatLng latLng= new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
protected synchronized void buildGoogleApiClient(){
googleApiClient=new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
googleApiClient.connect();
}
}
manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nitctraveltogether">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<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" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".demo"
android:label="#string/title_activity_demo"></activity>
<activity
android:name=".home"
android:label="#string/title_activity_home">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Splashscreen"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat
2020-03-08 17:19:31.144 28966-28966/com.example.nitctraveltogether E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nitctraveltogether, PID: 28966
java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
at com.google.maps.api.android.lib6.impl.bi.c(:com.google.android.gms.dynamite_mapsdynamite#200475065#20.04.75 (100400-0):26)
at com.google.android.gms.maps.internal.i.a(:com.google.android.gms.dynamite_mapsdynamite#200475065#20.04.75 (100400-0):139)
at ch.onTransact(:com.google.android.gms.dynamite_mapsdynamite#200475065#20.04.75 (100400-0):4)
at android.os.Binder.transact(Binder.java:675)
at com.google.android.gms.internal.maps.zza.zzb(Unknown Source:20)
at com.google.android.gms.maps.internal.zzg.setMyLocationEnabled(Unknown Source:109)
at com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(Unknown Source:112)
at com.example.nitctraveltogether.demo.onMapReady(demo.java:42)
at com.google.android.gms.maps.zzak.zza(Unknown Source:2)
at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source:12)
at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source:12)
at android.os.Binder.transact(Binder.java:675)
at cg.b(:com.google.android.gms.dynamite_mapsdynamite#200475065#20.04.75 (100400-0):2)
at com.google.maps.api.android.lib6.impl.be.run(:com.google.android.gms.dynamite_mapsdynamite#200475065#20.04.75 (100400-0):2)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
App is getting crashed while accessing this activity, I am trying to access current location through google map api in android studio and using firebase location. Please help me resolve this error, is there any mistake in manifest file or java file. I have written all the required permissions in manifest file but still the app is getting crashed while running. You can also check the logcat for the error.

You need to request for user's permission to access location.
Read more here:
https://developer.android.com/training/permissions/requesting

Related

Current Location(on Google Maps API) not showing in app [duplicate]

This question already has answers here:
How can I show current location on a Google Map on Android Marshmallow?
(3 answers)
Closed 5 years ago.
We have the Google Maps API working; however, current location will not show up in our app but will show up when redirected to Google Maps(app). We want the blue dot to show up in our app and not just when it is forwarded to Google Maps(app).
Here are some code snippets (we are using Android Studio V2.3.3):
Can anyone offer any guidance, please?
Here is our MapActivity.java
package com.example.administrator.bubbleproject;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng losAngeles = new LatLng(34.0522, -118.2437);
mMap.addMarker(new MarkerOptions().position(losAngeles).title("Los Angeles"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(losAngeles, 18.0f));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
}
Here is our Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.bubbleproject">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="BUBBLE"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:parentActivityName="com.example.administrator.bubbleproject.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".tracker1PageActivity"
android:parentActivityName=".MainActivity" />
<activity android:name=".settingsActivity" />
<activity android:name=".setupActivity" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapActivity"
android:label="#string/title_activity_map">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here are some screenshots of My app and Forwarded to google maps.
My guess is that in OnMapReady() your permission check is failing and it's executing the return; instead of calling mMap.setMyLocationEnabled(true); Set a breakpoint and check it.
My code to check this looks like the following:
public static boolean haveLocationPermission(Context context)
{
return ContextCompat.checkSelfPermission(context, permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(context, permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
Then call this snippet when you want to check permission:
// Enable my location if we have permission
if (haveLocationPermission(getActivity()))
{
try
{
mMap.setMyLocationEnabled(true);
}
catch (SecurityException e) {}
}
We also have Location Services turned on, but I'm not sure whether that is necessary for the map to show location (use GoogleApiClient with the LocationServices.API).
Edit: From the duplicate issue it looks like you do need Location Services turned on. https://stackoverflow.com/a/34582595/1022886

Unable to get current location problems (android, permission)

I've dev my first application and i make a simple map activity, but latitude and longitude are always 0. (when i start the activity the cursor should be set in the device location).
I set permission in manifest and get google-services.json file, but i still have this error:
E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services. Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
I think this is why I cant get correct longitude and latitude.
Activity code:
public class ********Activity extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
double latitude, longitude;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_locate_match);
buildGoogleApiClient();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
} else
Toast.makeText(this, "Not connected...", Toast.LENGTH_SHORT).show();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
public void onConnectionFailed(ConnectionResult arg0) {
Toast.makeText(this, "Failed to connect...", Toast.LENGTH_SHORT).show();
}
public void onConnectionSuspended(int arg0) {
Toast.makeText(this, "Connection suspended...", Toast.LENGTH_SHORT).show();
}
public void onConnected(Bundle arg0) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Log.i("Permission","problems");
return;
}
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.i("latitude",""+latitude);
Log.i("longitude",""+longitude);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng pos = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(pos).title("User Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pos));
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marcocreation.******">
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<application
android:allowBackup="true"
android:icon="#mipmap/soccer"
android:label="#string/app_name"
android:launchMode="singleTop"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<activity
android:name=".MainActivity"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.marcocreation.******.MainActivity" />
</activity>
<activity
android:name=".HomeUserActivity"
android:label="#string/title_activity_home_user"
android:theme="#style/AppTheme" />
<activity
android:name=".RegisterActivity"
android:label="#string/title_activity_register"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.marcocreation.*******.MainActivity" />
</activity>
<activity
android:name=".ProfileActivity"
android:label="#string/title_activity_profile"
android:theme="#style/AppTheme" />
<activity
android:name=".profileActivity2"
android:label="#string/title_activity_profile2"
android:theme="#style/AppTheme" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<activity
android:name=".locateMatchActivity"
android:label="#string/title_activity_locate_match">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.marcocreation.********.profileActivity2" />
</activity>
</application>
</manifest>
Gradle:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.facebook.android:facebook-android-sdk:4.+'
compile 'com.google.android.gms:play-services:8.4.0'
}
Reading the log, i saw "Permission:problems" so the app seems to not has the right permission.
You need to place the configuration file (google-services.json) generated by developer.google.com, as mentioned in the 2nd step of the official docs here
Please take a look at this post: GoogleService failed to initialize
It will help you
I think i solved my problem:
- i updated android studio and now i use
compile 'com.google.android.gms:play-services-maps:9.2.0'
compile 'com.google.android.gms:play-services:9.2.0'
instead of 8.4.0.
Now i'll create a new post, cause i'm going crazy to use maps

Need a Android Studio/OSMDroid Guide for a school project

I'm currently developping an App in a school/exam purpose.
I'm using Android Studio 2.0 and an OPO with 5.1.1 on it and a Nexus 7 with 6.0.1 !
The goal is to display the location of the device on a map, and to trace a route passing by waypoints (cultural buildings).
I have no problem displaying the map (I'm able to center it on my city and with a good zoom level)
Now I want to display the current location of the device.
I encounter problems with permissions..
My manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="alpha.testmap">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
// AUTORISATIONS
<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_WIFI_STATE" />
<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" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My MainActivity.java:
package alpha.testmap;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import org.osmdroid.api.IMapController;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
public class MainActivity extends Activity {
private LocationManager mLocMgr;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
//Can't find the class of this fonction --> REQUEST_LOCATION);
}else {
Location myLocation = LOCATION_SERVICE.FusedLocationApi.getLastLocaation(mGoogleApiClient);
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
//Can't find the class of this fonction --> REQUEST_LOCATION);
}
setContentView(R.layout.activity_main);
MapView map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
//Adding zoom ability
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
//Create a default point
IMapController mapController = map.getController();
mapController.setZoom(16);
GeoPoint ptStart = new GeoPoint(47.215576, -1.549089);
mapController.setCenter(ptStart);
GeoPoint ptTourLu = new GeoPoint(47.21545, -1.54624);
//GPS
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 100, (LocationListener) this);
}
}
Your problem with permissions is due to changes brought to Android 6.0 that requires you to ask permission at runtime instead of requesting at install like before.
You can read more here, under the "Manifest" section.

My Android Google Map can't load with all setup being accomplished, please check it out

I have check all settings, but it can't load the map with fragment but a zoom widget. It have no gridding. I have check the key but don't think it has any problem.
Below is my code.
manifest:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17"/>
<!-- TODO: Replace "com.example.hellomap" with your package name -->
<permission
android:name="com.example.hellomap.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.hellomap.permission.MAPS_RECEIVE"/>
<!-- The following four 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"/>
<!-- 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:label="#string/app_name"
android:icon="#drawable/ic_launcher">
<uses-library android:name="com.google.android.maps" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDQFrrAorDIMec2q4kcxO9Y4hanG8x1YI0"/>
<activity
android:name="MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
layout:
<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"
android:layout_below="#id/tv_location"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
code:
package com.example.hellomap;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements InfoWindowAdapter{
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
#Override
public View getInfoContents(Marker arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoWindow(Marker arg0) {
// TODO Auto-generated method stub
return null;
}
}
Make sure that you have activated android map v2 api on google console.
you have created proper android key by entering correct SHA1 and package name on google console.
try to run it on physical device.
Make sure you have "Google Repository" installed from the SDK manager. They never mention this in the instructions but this must be installed alongside the Google Play Services SDK for everything to function.
Because I'm in China, it's not convenient to access Google server. Therefore I used a proxy to make the network can access the Google and then everything goes well. Thank all you guys for responding and special thank to #Yazan who gave me a prompt.

How to drop a marker on the users location in Google Maps v2

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

Categories

Resources