How to add overlay in google maps API v2 | Android |

32,811

Solution 1

You can add a marker in the onCreate of your FragmentActivity.

        GoogleMap googleMap;
        googleMap = ((SupportMapFragment)(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();
        LatLng latLng = new LatLng(-33.796923, 150.922433);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.addMarker(new MarkerOptions()
                .position(latLng)
                .title("My Spot")
                .snippet("This is my spot!")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        googleMap.getUiSettings().setCompassEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));

The end to end solution would look like this for the layout...

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />

...the Activity like this...

public class NameOfYourActivity extends FragmentActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.nameOfYourLayout);

    GoogleMap googleMap;
    googleMap = ((SupportMapFragment)(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();
    LatLng latLng = new LatLng(-33.796923, 150.922433);
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googleMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title("My Spot")
            .snippet("This is my spot!")
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
    googleMap.getUiSettings().setCompassEnabled(true);
    googleMap.getUiSettings().setZoomControlsEnabled(true);
    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
}

Solution 2

https://developers.google.com/maps/documentation/android-api/groundoverlay

LatLng NEWARK = new LatLng(40.714086, -74.228697);

GroundOverlayOptions newarkMap = new GroundOverlayOptions()
        .image(BitmapDescriptorFactory.fromResource(R.drawable.newark_nj_1922))
        .position(NEWARK, 8600f, 6500f);
map.addGroundOverlay(newarkMap);

Solution 3

Not sure if you still need a hand on this, but here is what worked for me.

Since you are loading the fragment into a container, it's taking time to load the fragment components into memory and hence the map is null. To remedy this, I grab and populate the map in the onAttachedToWindow() method of my activity while still creating and adding the fragment to the container in the onCreate method. This gives the fragment time to load since this event fires when the window has been loaded.

SupportMapFragment mMapFragment;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

    // Try to obtain the map from the SupportMapFragment.
    mMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag(MAP_FRAG_NAME);

    // Not found so make a new instance and add it to the transaction for swapping
    if (mMapFragment == null) {
        mMapFragment = SupportMapFragment.newInstance();
        ft.add(R.id.fragment_container, mMapFragment, MAP_FRAG_NAME);
    }

    ft.commit();
}

@Override
    public void onAttachedToWindow() {
        // Load the map here such that the fragment has a chance to completely load or else the GoogleMap value may be null
        GoogleMap googleMap;
googleMap = (mMapFragment).getMap();
LatLng latLng = new LatLng(-33.796923, 150.922433);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.addMarker(new MarkerOptions()
        .position(latLng)
        .title("My Spot")
        .snippet("This is my spot!")
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));

        super.onAttachedToWindow();
    }

hope this helps.

Regards, DMan

Share:
32,811
Malaka
Author by

Malaka

High School Student | Interesting in Android and Java programming | Beginner experience seeking for answers, help, and guidance.

Updated on July 19, 2022

Comments

  • Malaka
    Malaka almost 2 years

    I recently got working with Google Maps API v2 on Android and stumbled upon another obstacle. I cannot figure out how to add an overlay such as in API v1 to display a marker on certain locations using lat and long. I also want it to start in the same town using long and lat. I so far added some code in for the starting position of map BUT it didn't work. I guess I should write it all in java instead of the XML layout but I don't know how to address SupportMapFragment to do anything.

    This is main activity, I am using SUPPORTMAPFRAGMENT instead of MapFragment and would prefer not to switch.

    package com.example.maps;
    
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import com.google.android.gms.maps.SupportMapFragment;
    
    public class Main extends FragmentActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        SupportMapFragment fragment = new SupportMapFragment();
        getSupportFragmentManager().beginTransaction()
                .add(android.R.id.content, fragment).commit();
        }
    }
    

    This is XML

    <?xml version="1.0" encoding="utf-8"?>
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
      android:id="@+id/map"
       android:name="com.google.android.gms.maps.SupportMapFragment"
       android:layout_width="wrap_content"
       android:layout_height="match_parent"
       map:cameraBearing="112.5"
       map:cameraTargetLat="-33.796923"
       map:cameraTargetLng="150.922433"
       map:cameraTilt="30"
       map:cameraZoom="13"
       map:mapType="normal"
       map:uiCompass="false"
       map:uiRotateGestures="true"
       map:uiScrollGestures="false"
       map:uiTiltGestures="true"
       map:uiZoomControls="false"
       map:uiZoomGestures="true" />
    

    EDIT

    New Java code( I excluded imports and package but they are all there. )

    public class Main extends FragmentActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        SupportMapFragment fragment = new SupportMapFragment();
        getSupportFragmentManager().beginTransaction()
                .add(android.R.id.content, fragment).commit();
    
        GoogleMap googleMap;
        googleMap = ((SupportMapFragment)(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();
        LatLng latLng = new LatLng(-33.796923, 150.922433);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.addMarker(new MarkerOptions()
                .position(latLng)
                .title("My Spot")
                .snippet("This is my spot!")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        googleMap.getUiSettings().setCompassEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
    }
    

    }

    New errors

    01-02 01:16:53.333: D/AndroidRuntime(916): Shutting down VM
    01-02 01:16:53.333: W/dalvikvm(916): threadid=1: thread exiting with uncaught    exception (group=0x40a70930)
    01-02 01:16:53.363: E/AndroidRuntime(916): FATAL EXCEPTION: main
    01-02 01:16:53.363: E/AndroidRuntime(916): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.maps/com.example.maps.Main}: java.lang.NullPointerException
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.os.Handler.dispatchMessage(Handler.java:99)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.os.Looper.loop(Looper.java:137)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.app.ActivityThread.main(ActivityThread.java:5039)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at java.lang.reflect.Method.invokeNative(Native Method)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at java.lang.reflect.Method.invoke(Method.java:511)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at dalvik.system.NativeStart.main(Native Method)
    01-02 01:16:53.363: E/AndroidRuntime(916): Caused by: java.lang.NullPointerException
    01-02 01:16:53.363: E/AndroidRuntime(916):  at com.example.maps.Main.onCreate(Main.java:19)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.app.Activity.performCreate(Activity.java:5104)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    01-02 01:16:53.363: E/AndroidRuntime(916):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    01-02 01:16:53.363: E/AndroidRuntime(916):  ... 11 more
    
  • Malaka
    Malaka over 11 years
    I'll try this out and report my findings. How about making those markers click able? OnClickListener?
  • Aaron McIver
    Aaron McIver over 11 years
    You can use the OnMarkerClickListener, with additional information here.
  • Malaka
    Malaka over 11 years
    I tried it. New code back at original post/question. It crashes now on launch. I will be working(recreating) it tomorrow during my visit to my school tech and I will be on my main workspace computer at that moment. I will do most of my work there and would appreciate if I can have this working by then(EST 1/2/2013 12PM-4PM). I appreciate all your help so far.
  • Aaron McIver
    Aaron McIver over 11 years
    @Malaka Edited my answer to provide a more comprehensive answer on what the end to end solution would look like.
  • Malaka
    Malaka over 11 years
    On the latlng line that you assigned a name to the value. I can make multiple of them and add multiple markers right? I need to display nearly 20 different markers. I apologize if I'm irritating. I have a deadline soon and am very new to this.
  • Aaron McIver
    Aaron McIver over 11 years
    @Malaka Yes you can add multiple markers. I would suggest getting this initial question solved and then asking a new one as you get more granular, versus the ongoing dialog via the comments as that will not serve users well down stream.