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

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();

Related

trying to get current location on my google-map

I'm trying to get my current location on google map but it's giving me a blank map.
this is my fragment
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationSource.OnLocationChangedListener, GoogleMap.OnMapClickListener {
private GoogleMap mMap;
private LatLng userLocation;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
public LocationManager mLocationManager;
#Override
protected void onCreate(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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
#Override
public void onLocationChanged(Location location) {
userLocation = new LatLng(location.getAltitude(), location.getLongitude());
Toast.makeText(this, "found you...", Toast.LENGTH_SHORT).show();
MarkerOptions markerOptions= new MarkerOptions();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 10));
mMap.addMarker(new MarkerOptions().position(userLocation).title("you are here"));
}
#Override
public void onMapClick(LatLng latLng) {
}
}
then that's my manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="25" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBuSE2O0siczDYt3oh3FVUgcO_MZs4-8FQ" />
<!-- To access Google+ APIs: -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.example.liadiluz.finalproject.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:name="android.support.multidex.MultiDexApplication"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".services.MyIntentService"
android:exported="false" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".Activities.MapsActivity"
android:label="#string/title_activity_maps2"></activity>
</application>
and that's the layout file
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.liadiluz.finalproject.Activities.MapsActivity" />
</RelativeLayout>

Can't setup Google map v2

I am trying over a week to setup my Google Map v2. but its not working for me.I tried answers from questions related to it but no use.i couldn't track the exact problem.please help.
Here is my xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</RelativeLayout>
In my map.class I have
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.*;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment;
import android.app.Activity;
import android.app.Dialog;
import android.support.v4.app.Fragment;
import android.widget.Toast;
import android.os.Bundle;
public class Map extends Activity {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
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();
}
}
}
}
My API key is correct and I imported google play services library as per the directions.In my manifest file
<permission
android:name="com.example.sellatease.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.sellatease.permission.MAPS_RECEIVE" />
<uses-sdk
android:minSdkVersion="21"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<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" />
and
<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="AIzaSyCwHLxfMRBnD_MJDQDV9IYBZTxbkCVlZsA" />
This is my error log
And in console I got can not find googleplayserviceslib.apk error too.
new error log
you need to extend FragmentActivity/AppCompatActivity if you are using SupportMapFragment.
public class Map extends FragmentActivity/AppCompatActivity {
And
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
googleMap = mySupportMapFragment.getMap();
You can check Android Map V2
Try this
googleMap = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
Try this...
activity_map.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</RelativeLayout>
Map.java
public class Map extends android.support.v4.app.FragmentActivity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
AndroidManifest.xml
....
<permission
android:name="com.example.sellatease.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-sdk
android:minSdkVersion="21"
android:targetSdkVersion="21" />
<uses-permission
android:name="com.example.sellatease.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<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" />
<application
android:icon="#drawable/ic_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="AIzaSyCwHLxfMRBnD_MJDQDV9IYBZTxbkCVlZsA" />
<activity
android:name=".Map"
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>
....
UPDATE
Create Google map programatically.
activity_map.xml
<FrameLayout
android:gravity="top"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/mapContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Map.java
public class Map extends AppCompatActivity{
private GoogleMap mMap;
private SupportMapFragment mMapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mMapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.mapContainer, mMapFragment, "map");
fragmentTransaction.commit();
mMapFragment.getMapAsync(mapReadyCallback);
}
private OnMapReadyCallback mapReadyCallback = new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
mMap.setTrafficEnabled(true);
mMap.setIndoorEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
}
};

NPE when adding GoogleMap in fragment

Here's my my_location.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etName" />
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Here's my code:
public class MyLocation extends Fragment {
private GoogleMap googleMap;
Context mContext;
public MyLocation (){ mContext = getActivity(); };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View root = inflater.inflate(R.layout.my_location, container, false);
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
Unfortunately, it displays NPE at the line
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
What did I do wrong?
In case, parts of my manifest
<permission
android:name="com.imincode.meniti.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.imincode.meniti.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<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"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Solved my problem with the link given in the accepted answer! Here's what I did:
I just changed
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
to
googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();
Your issue is same with link1 link2 link3
Please do some search before ask a question.
The issue is because it takes time for google map to load ( if you're using inside a fragment, you can expect this load time to be huge) and when you try to access map before it is being loaded, you'll get NullPointerException saying map reference went null. You should wait for the map to load first and then you should access the map views. You have pre-defined callback for that and here is how you should use it.
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap map) {
googleMap = map; }
});

how to use maps inside the fragment

i can show plain guide in inside part i have to add marker to specific geolocation
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="100dp"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
I don't did anything in java code however i extended my class with Fragment
Don't forget to add google-play-service-lib as a library project and
it should sharing the same workspace of your project
Java code
public class SomeFragment extends Fragment {
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_key"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".HomeActivity"
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>
Edit: After your edit new question arise.
After initializing map check if it is not null from official documentation
if(map != null)
{
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183))
.title("San Francisco")
.snippet("Population: 776733"));
}
In your layout, replace your code with this one :
<RelativeLayout
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="100dp">
</RelativeLayout>
and in your code :
private SupportMapFragment supportMapFragment;
private GoogleMap map;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
supportMapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (supportMapFragment == null) {
supportMapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, supportMapFragment).commit();
}
}
#Override
public void onResume() {
super.onResume();
...
map = supportMapFragment.getMap();
...
}

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)

Categories

Resources