Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android Google Maps V2 - MapView in XML
<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>
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();
}
}
<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"/>
<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>
@sabonis

This comment has been minimized.

Copy link

commented Jun 15, 2013

You make my life more easier.
Thank you.

@ajmdonker

This comment has been minimized.

Copy link

commented Jul 28, 2013

Awesome, thanks!

As a starting Android Developer I was wondering how to do this; I was close, but your code pushed me in the right direction.

@chrisban

This comment has been minimized.

Copy link

commented Nov 4, 2013

Wow thanks so much for this code! I was so close, but couldn't find any help anywhere online until I stumbled across this example code!

You're a lifesaver!!!

@rmujica

This comment has been minimized.

Copy link

commented Nov 26, 2013

thanks for you gist, as others said, it's a lifesaver!!

@mzaneb

This comment has been minimized.

Copy link

commented Dec 16, 2013

im getting this crash while using fregment.help will be appreciated

12-17 01:56:57.759: E/AndroidRuntime(25080): FATAL EXCEPTION: main
12-17 01:56:57.759: E/AndroidRuntime(25080): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example/com.example.HomeActivity}: java.lang.ClassNotFoundException: com.example.HomeActivity in loader dalvik.system.PathClassLoader[/data/app/com.example-2.apk]
12-17 01:56:57.759: E/AndroidRuntime(25080): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1573)
12-17 01:56:57.759: E/AndroidRuntime(25080): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
12-17 01:56:57.759: E/AndroidRuntime(25080): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-17 01:56:57.759: E/AndroidRuntime(25080): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
12-17 01:56:57.759: E/AndroidRuntime(25080): at android.os.Handler.dispatchMessage(Handler.java:99)
12-17 01:56:57.759: E/AndroidRuntime(25080): at android.os.Looper.loop(Looper.java:123)
12-17 01:56:57.759: E/AndroidRuntime(25080): at android.app.ActivityThread.main(ActivityThread.java:3687)
12-17 01:56:57.759: E/AndroidRuntime(25080): at java.lang.reflect.Method.invokeNative(Native Method)
12-17 01:56:57.759: E/AndroidRuntime(25080): at java.lang.reflect.Method.invoke(Method.java:507)
12-17 01:56:57.759: E/AndroidRuntime(25080): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
12-17 01:56:57.759: E/AndroidRuntime(25080): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
12-17 01:56:57.759: E/AndroidRuntime(25080): at dalvik.system.NativeStart.main(Native Method)
12-17 01:56:57.759: E/AndroidRuntime(25080): Caused by: java.lang.ClassNotFoundException: com.example.HomeActivity in loader dalvik.system.PathClassLoader[/data/app/com.example-2.apk]
12-17 01:56:57.759: E/AndroidRuntime(25080): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
12-17 01:56:57.759: E/AndroidRuntime(25080): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
12-17 01:56:57.759: E/AndroidRuntime(25080): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
12-17 01:56:57.759: E/AndroidRuntime(25080): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-17 01:56:57.759: E/AndroidRuntime(25080): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1565)
12-17 01:56:57.759: E/AndroidRuntime(25080): ... 11 more

@pawegio

This comment has been minimized.

Copy link

commented Jan 20, 2014

Perfect solution! I felt powerless trying to find a way for working nested MapFragment... and you made my day!

@incrediblecube

This comment has been minimized.

Copy link

commented Jan 22, 2014

Really helpful thanks!

@dgoulston

This comment has been minimized.

Copy link

commented Jan 28, 2014

Thank you so much, trying to get FragmentMap working with a Fragment class was causing issue, glad I can use mapview, your example made it soo easy.

@akky777

This comment has been minimized.

Copy link

commented Feb 7, 2014

i have a problem in this program...

@dharshan4help

This comment has been minimized.

Copy link

commented Feb 28, 2014

when i try this snippet, at run time it is showing error as "cannot be cast to android app activity". What is the reason .?

@zilppuri

This comment has been minimized.

Copy link

commented Apr 23, 2014

Uh.. finally got Map View working inside tabbed interface. Thanks!

@alvarosantisteban

This comment has been minimized.

Copy link

commented Jun 17, 2014

Thanks! Just some comments:

  • The GooglePlayServicesNotAvailableException seems like can not get triggered.
  • In the manifest, I needed to add the following:
<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

and

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
@Bhavdip

This comment has been minimized.

Copy link

commented Jun 25, 2014

thank you for share map view with google map v2 , I was searching instead of using nested fragment how to implement the MapView in layout and I done with your help.

@tushar91sakhuja

This comment has been minimized.

Copy link

commented Jul 27, 2014

here below are some errors coming in this program

07-27 06:31:42.667: E/AndroidRuntime(5289): FATAL EXCEPTION: main
07-27 06:31:42.667: E/AndroidRuntime(5289): Process: com.example.mapes, PID: 5289
07-27 06:31:42.667: E/AndroidRuntime(5289): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.mapes/com.example.mapes.MainActivity}: java.lang.ClassCastException: com.example.mapes.MainActivity cannot be cast to android.app.Activity
07-27 06:31:42.667: E/AndroidRuntime(5289): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
07-27 06:31:42.667: E/AndroidRuntime(5289): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
07-27 06:31:42.667: E/AndroidRuntime(5289): at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-27 06:31:42.667: E/AndroidRuntime(5289): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-27 06:31:42.667: E/AndroidRuntime(5289): at android.os.Handler.dispatchMessage(Handler.java:102)
07-27 06:31:42.667: E/AndroidRuntime(5289): at android.os.Looper.loop(Looper.java:136)
07-27 06:31:42.667: E/AndroidRuntime(5289): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-27 06:31:42.667: E/AndroidRuntime(5289): at java.lang.reflect.Method.invokeNative(Native Method)
07-27 06:31:42.667: E/AndroidRuntime(5289): at java.lang.reflect.Method.invoke(Method.java:515)
07-27 06:31:42.667: E/AndroidRuntime(5289): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-27 06:31:42.667: E/AndroidRuntime(5289): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-27 06:31:42.667: E/AndroidRuntime(5289): at dalvik.system.NativeStart.main(Native Method)
07-27 06:31:42.667: E/AndroidRuntime(5289): Caused by: java.lang.ClassCastException: com.example.mapes.MainActivity cannot be cast to android.app.Activity
07-27 06:31:42.667: E/AndroidRuntime(5289): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
07-27 06:31:42.667: E/AndroidRuntime(5289): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
07-27 06:31:42.667: E/AndroidRuntime(5289): ... 11 more

Hope someone help me in solving my problem.........

@matheusjardimb

This comment has been minimized.

Copy link

commented Aug 18, 2014

mapView.getMap(); is always returning null to me. Any tip?

@matheusjardimb

This comment has been minimized.

Copy link

commented Aug 18, 2014

I waste a few hours only because AndroidStudio have suggested me to change `compile 'com.google.android.gms:play-services:5.0.89'tocompile 'com.google.android.gms:play-services:5.2.08'``. Don't use preview Play Services version.

@smittysauce

This comment has been minimized.

Copy link

commented Sep 1, 2014

I was also getting mapView.getMap(); returning NULL. After tweaking the onCreateView() I was able to capturing the problem - the Android virtual device I was running in the emulator did not have the Google APIs installed on it - see to fix: http://stackoverflow.com/questions/22141043/google-play-services-missing-in-emulator-android-4-4-2

You may also end up going down the rabbit hole trying to get Play service to run on your particular emulator - http://stackoverflow.com/q/13691943/194872

Here is the tweaked onCreateView which will capture any Google play problems:

@override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map_schedule, container, false);

    int statusCode = com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(this.getActivity());
    switch (statusCode)
    {
        case ConnectionResult.SUCCESS:
            Toast.makeText(this.getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
            break;
        case ConnectionResult.SERVICE_MISSING:
            Toast.makeText(this.getActivity(), "SERVICE MISSING", Toast.LENGTH_SHORT).show();
            break;
        case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
            Toast.makeText(this.getActivity(), "UPDATE REQUIRED", Toast.LENGTH_SHORT).show();
            break;
        //
        // see http://developer.android.com/reference/com/google/android/gms/common/ConnectionResult.html for error code translation!!!
        //
        default: Toast.makeText(this.getActivity(), "Play Service result " + statusCode, Toast.LENGTH_SHORT).show();
    }

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

// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
return v;

}

@BenjaminPiette

This comment has been minimized.

Copy link

commented Oct 1, 2014

Great stuff, thanks

@fahadishaque35

This comment has been minimized.

Copy link

commented Dec 2, 2014

Keep in mind mapView.onResume() draws the map else user would only see a grid box.

@aminalzanki

This comment has been minimized.

Copy link

commented Dec 16, 2014

thanks! very useful

@saravanarajan

This comment has been minimized.

Copy link

commented Feb 10, 2015

Thanks dude... its very useful and working perfectly....

@fnk0

This comment has been minimized.

Copy link

commented Feb 11, 2015

This gist saved me so much frustration! Thank you!

@Dimoy

This comment has been minimized.

Copy link

commented Mar 14, 2015

Great ...thanks a lot for this help

@msaleem87

This comment has been minimized.

Copy link

commented Mar 15, 2015

Greate ... thank you for this help.

@igofed

This comment has been minimized.

Copy link

commented Mar 20, 2015

If someone want to use this code not inside fragment - you should add mapView.onResume(), or you will have no tiles before touch on map.

@mohsinraza

This comment has been minimized.

Copy link

commented Apr 27, 2015

very nice..... Thank you

@axierjhtjz

This comment has been minimized.

Copy link

commented Jun 19, 2015

Nice example ;)

@positivelymade

This comment has been minimized.

Copy link

commented Jun 23, 2015

Thanks.

Note that getMap() is now deprecated, use getMapAsync(this)

@riyase

This comment has been minimized.

Copy link

commented Jul 2, 2015

@igofed thanks for the point

@Ricardo1980

This comment has been minimized.

Copy link

commented Jul 6, 2015

Thanks!

Can I call super before the map?

public void onResume() {
super.onResume();
mapView.onResume();
}

@yomigits

This comment has been minimized.

Copy link

commented Jul 25, 2015

This is great. Please how can I add sliding menu to this map ? want it to be a page of the side menu.

@AdrianAlcGon

This comment has been minimized.

Copy link

commented Aug 17, 2015

Awesome, thanks! :DD
My hero! XD

@Paulpeter

This comment has been minimized.

Copy link

commented Aug 30, 2015

Thank you so much, you have made my learnng a lot easier ...bless

@al3xpisani

This comment has been minimized.

Copy link

commented Sep 28, 2015

I have to touch at screen to get the map updated. Would you help me please with this issue ... thx

onResume did the trick.... :(

@Override
public void onResume() {
    mapView.onResume();
    super.onResume();
}
@kafukafienkov

This comment has been minimized.

Copy link

commented Dec 20, 2015

Thanks mate ;)

@roger35972134

This comment has been minimized.

Copy link

commented Jan 28, 2016

Thanks a lot :)

@Atwa

This comment has been minimized.

Copy link

commented Mar 4, 2016

Thnx Dude , you made my day ^^

@repl-krishna-g

This comment has been minimized.

Copy link

commented Mar 29, 2016

Used the exact code inside Dialog. But not showing the map

@Nordin-010

This comment has been minimized.

Copy link

commented Apr 8, 2016

I wasted a whole day, just because I didn't add onResume() :( This is crazy, but thnx to the owner of this gist, may Allah bless you.

@sankar07

This comment has been minimized.

Copy link

commented Aug 29, 2016

Getting inflating error
android.view.InflateException: Binary XML file line #37: Binary XML file line #37: Error inflating class com.google.android.gms.maps.MapView

@ravirajjak

This comment has been minimized.

Copy link

commented Sep 5, 2016

Have you tried for Marshmallow? I am getting error EGL BAD DISPLAY.

@ghost

This comment has been minimized.

Copy link

commented Nov 7, 2016

Thanks man. Instead of searching the location by lat long I want to search it by Name of place or institutions,How can I do it?Please help

@prasad-mattaparthi

This comment has been minimized.

Copy link

commented Jan 7, 2017

Thankyou its very usefull...

@TitikshaDaga

This comment has been minimized.

Copy link

commented Sep 4, 2017

How have you used this fragment? My MainActivity extends FlutterActivity so how should I proceed?

@yamenr

This comment has been minimized.

Copy link

commented Mar 15, 2018

When adding MapView to my XML I get the following error:

could not find dependency "com.google.android.gms:play-services-maps:11.8.0"

What to do?

@Eido95

This comment has been minimized.

Copy link

commented Jun 10, 2018

Thank you very much for this code.

Further code about MapView can be found at Google Maps Android Samples RawMapViewDemoActivity sample, and Maps SDK for Android Map Objects MapView guide.

After combining this gist code with the above mentioned links, I found it to work.

@raanaYavari

This comment has been minimized.

Copy link

commented Jun 11, 2019

Thank you for this code.
How can I find current location with mapview?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.