I have created activity: MapsActivity, which shows my location on map.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager locationManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
double lat = location.getLatitude();
double lng = location.getLongitude();
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);
// Add a marker in Sydney and move the camera
LatLng place = new LatLng(lat,lng);
mMap.addMarker(new MarkerOptions().position(place).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place));
}
}
I created MainActivity, with a button, which I want to click to move to MapsActivity, here it's code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showMyLocation(View view){
Intent intentControls = new Intent(this, MapsActivity.class);
startActivity(intentControls);
}
}
Gradle
android {
compileSdkVersion 27
buildToolsVersion "27.0.1"
defaultConfig {
applicationId "com.example.lukasz.aaaaa"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.google.android.gms:play-services-maps:10.2.6'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8'
testCompile 'junit:junit:4.12'
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lukasz.aaaaa">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<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">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
</activity>
<activity android:name=".MainActivity"
android:label="Mapy">>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
The problem is, that after I click the button in my MainActivity, the application crashes with
FATAL EXCEPTION: main
Process: com.example.lukasz.aaaaa, PID: 2433
java.lang.IllegalArgumentException: invalid provider: null
at android.location.LocationManager.checkProvider(LocationManager.java:2099)
at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1200)
at com.example.lukasz.aaaaa.MapsActivity.onMapReady(MapsActivity.java:56)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source:7)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source:30)
at android.os.Binder.transact(Binder.java:627)
at gl.b(:com.google.android.gms.DynamiteModulesB#11577470:20)
at com.google.android.gms.maps.internal.bf.a(:com.google.android.gms.DynamiteModulesB#11577470:5)
at com.google.maps.api.android.lib6.impl.bc.run(:com.google.android.gms.DynamiteModulesB#11577470:5)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)r
My question is how do I run Google Map Activity from another activity, using Intent?
keep below permission above application Tag
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
......
.....
<activity>
.....
</activity>
</application>
(or)
You are getting this error most probably, due to un-availability of
GPS Providers. Please ask the person to check settings if Gps
Provider or Network Provider has been enabled into Location
settings.
Related
In my android app, with a Navigation Drawer, I have a problem with a fragment in which I use a mapview: when i launch the fragment for the first time, it shows only the first of one list of markers I want to draw. I have to reload the fragment to see all the markers draw on the map (or for example click on another voice on the menu and after again on the map fragment). I have the feeling that the fragment launch the map before all the markers are draw. Can it be the problem? How could I fix it? This is my code:
public class MapFragment extends Fragment implements OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener {
private GoogleMap mGoogleMap;
private MapView mMapView;
private View mView;
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mView = inflater.inflate(R.layout.map_fragment, container, false);
return mView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = mView.findViewById(R.id.map);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
drawMarkerOnTheMap(mGoogleMap);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng city = new LatLng(40.679425, 14.755968);
CameraPosition camera = CameraPosition.builder().target(city).zoom(15).build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(camera));
}
private void drawMarkerOnTheMap(GoogleMap googleMap) {
try {
InputStream is = getContext().getAssets().open("turisticpoint.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element=doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("turisticpoint");
for (int i=0; i<nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
String title = getValue("title", element2);
String tit = getContext().getResources().getString(getContext().getResources().getIdentifier(title, "string", getActivity().getPackageName()));
Double latitude = Double.valueOf(getValue("latitude", element2));
Double longitude= Double.valueOf(getValue("longitude", element2));
LatLng position = new LatLng(latitude, longitude);
MarkerOptions marker = new MarkerOptions().
position(position).
title(tit)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
googleMap.addMarker(marker);
}
}
} catch (Exception e) {e.printStackTrace();}
}
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
}
In my logcat I just found this error:
E/libprocessgroup: failed to make and chown /acct/uid_10063: Read-only file system
this is my manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="package">
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<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">
<activity
android:name=".HomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<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.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MainActivity"
android:label="MyApp"
android:theme="#style/AppTheme.NoActionBar"></activity>
</application>
</manifest>
and my build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "myappId"
minSdkVersion 15
targetSdkVersion 28
multiDexEnabled true
versionCode 16
versionName "1.5"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
missingDimensionStrategy 'minApi', 'minApi18', 'minApi23'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
and this is an xml file similar to mine:
<records>
<turisticpoint>
<titolo>Gardens</titolo>
<latitudine>40.678480</latitudine>
<longitudine>14.753152</longitudine>
</turisticpoint>
<turisticpoint>
<titolo>Castle</titolo>
<latitudine>40.6794731</latitudine>
<longitudine>14.7544442</longitudine>
</turisticpoint>
<turisticpoint>
<titolo>Beach</titolo>
<latitudine>40.6965378</latitudine>
<longitudine>14.7777038</longitudine>
</turisticpoint>
</records>
in total I have 13 turistic point.
I am looking to display a Google Maps Display on a fragment layout within android studio. I have already downloaded Google play services in the SDK and have made the appropriate changes to my gradle files (I Think). I have made some changes to the android manifest file as well to grant user permissions etc. At run time a google maps display renders but the lng and lat are set to 0 so when the map displays, it shows me an area around Africa. I have made methods in the java file such as onMapReady, which is supposed to display the map at a different location and have it more zoomed in. The onMapReady function calls another method called goToLocationZoom, which holds the required functionality to allow the map to move to this location but for some reason everytime I run it, it always stays to the area around Africa, even though I have changed the lng and lat values. I am following a tutorial to achieve this, and in there Activty_home.XML file, they have their layout to linear, whilst mine is set to constraint but I don't think this would cause the issue. Does anyone know how to display the map to the lng and lat values that I have specified in the java file?
Below is my Java file code:
com.example.cmpkbest.lifestylefitnessapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
public class ViewLifestyles extends AppCompatActivity implements
GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_lifestyles);
initMap();
}
private void initMap () {
MapFragment mapFragment = (MapFragment) getFragmentManager ().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
goToLocationZoom (53.408743, -2.984154, 15);
}
private void goToLocation (double lat, double lng) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
mGoogleMap.moveCamera(update);
}
private void goToLocationZoom (double lat, double lng, float zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mGoogleMap.moveCamera(update);
}
}
Below is my Manifest code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cmpkbest.lifestylefitnessapp">
<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" />
<permission android:name="com.example.cmpkbest.lifestylefitnessapp.permission.MAPS_RECIEVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.cmpkbest.lifestylefitnessapp.permission.MAPS_RECIEVE" />
<uses-permission android:name="com.google.android.providers.gsf.permissions.READ_GSERVICES" />
<uses-feature android:glEsVersion="0x00020000"
android:required="true" />
<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" >
<activity android:name=".RegistrationPage">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Login" />
<activity android:name=".Home" />
<activity android:name=".ViewLifestyles" />
<activity android:name=".Workouts" />
<activity android:name=".Notemaker"></activity>
<meta-data android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAkAQlA2B8_E5pPNH_jdAWSJpf915uozi8 " />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
Below is my Gradle Files:
apply plugin: 'com.android.application'
repositories {
maven {
url 'https://maven.google.com'
}
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.example.cmpkbest.lifestylefitnessapp"
minSdkVersion 23
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:+'
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services-maps:11.0.4'
}
Finally, my Layout.XML file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg5"
tools:context="com.example.cmpkbest.lifestylefitnessapp.ViewLifestyles"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<fragment
android:id="#+id/mapFragment"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="346dp"
android:layout_height="212dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintVertical_bias="0.084" />
</android.support.constraint.ConstraintLayout>
I also had a project doing same output. I handle it this way.
So first you have to initialize the map
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (mMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Then i call setUpMap right after initializing it, not relying on onMapReady
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
lastLocation.getLatitude(), lastLocation.getLongitude()), 15));
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setIndoorEnabled(true);
mMap.setMyLocationEnabled(true);
Hope this helps
I have a google map in a fragment in my application. Funny thing is that the map loads, but the logcat displays a NullPointerException, and I only noticed it when tried to update the camera on the map so that it could automatically zoom in on the marker. Only then the map will crash. Otherwise, the map loads fine in the fragment but with no marker (even though I am adding one using my current gps location).
EDITED*
I understand that its crashing because the googleMap is null, but I don't understand why it's returning null. The map renders and well I've done this before and it usually crashes at that point. Doesn't render.
Here is the logcat error
05-08 01:30:33.143 30130-30130/com.example.javed_000.famjam E/mapApp﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
05-08 01:30:33.152 30130-30130/com.example.javed_000.famjam E/MapFragment﹕ lat = 10.7270913 and Long = -61.5544451
05-08 01:30:33.155 30130-30130/com.example.javed_000.famjam D/AndroidRuntime﹕ Shutting down VM
05-08 01:30:33.156 30130-30130/com.example.javed_000.famjam E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.javed_000.famjam, PID: 30130
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.animateCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference
at com.example.javed_000.famjam.MapFragment.getLocation(MapFragment.java:60)
at com.example.javed_000.famjam.MapFragment.onCreateView(MapFragment.java:33)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:488)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:555)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:514)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:495)
at com.example.javed_000.famjam.SlidingTabLayout$TabClickListener.onClick(SlidingTabLayout.java:283)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
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.javed_000.famjam" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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="AIzaSyAhgnZ7ESL-EIRS4Da_hGw_7u9IQI3SZE0" />
<activity
android:name=".SignInActivity"
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=".MainActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
This is my dependencies in the gradle file
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:7.0.0'
compile 'com.google.android.gms:play-services-maps:7.0.0'
}
This is my layout file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/mapView"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Here is my code snippet from the Map Fragment
private void createMapView(){
try {
if(googleMap == null){
SupportMapFragment smf = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapView);
googleMap = smf.getMap();
if(googleMap == null) {
Toast.makeText(getActivity().getBaseContext(),
"Error creating map", Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception){
Log.e("mapApp", exception.toString());
}
}
private void getLocation(){
gps = new GPSTracker(this.getActivity());
if(gps.CanGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Log.e("MapFragment","lat = " + latitude + " and Long = " + longitude);
addMarker(latitude,longitude);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude), 12));
} else {
gps.showSettingsAlert();
}
}
private void addMarker(double lat, double lng){
if(googleMap != null){
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title("Marker")
.draggable(true)
);
}
}
googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();
This worked for me. getSupportFragmentManager() seemed to be causing all the crashes.
MainActivity.xml :
<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"/>
MainActivity.java :
Private GoogleMap GoogleMap;
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
Here's the permission:
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
And here's the metadata section:
...
<meta-data android:name="com.google.android.maps.v2.API_KEY"
android:value="HERE GOES YOUR API KEY" />
Just do like the below
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
map = googleMap;
map.setMyLocationEnabled(true);
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
}
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.
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)