android – How to show multiple markers on MapFragment in Google Map API v2?-ThrowExceptions

Exception or error:

I am using Google Map API v2 in my application to show Maps.

I have followed all the steps, that is to be followed to enable Google Map in my application.

public class PinLocationOnMapView extends FragmentActivity {

    private double mLatitude = 0.0, mLongitude = 0.0;

    protected void onCreate(Bundle savedInstanceState) {

        SupportMapFragment fragment = SupportMapFragment.newInstance();
                .add(, fragment).commit();

If I use this code, it shows me map, but if I provide my latitude/longitude values, map tiles does not load, and I see only white tiles.

Following is the code written in onCreate() of above class:

 if (getIntent().getExtras() != null) {
            final Bundle bundle = getIntent().getBundleExtra("LOCATION");
            mLatitude = bundle.getDouble("LATITUDE");
            mLongitude = bundle.getDouble("LONGITUDE");
        } else {

        GoogleMapOptions options = new GoogleMapOptions();
        LatLng latLng = new LatLng(mLatitude, mLongitude);
        CameraPosition cameraPosition;// = new CameraPosition(latLng, 0, 0, 0);
        cameraPosition = CameraPosition.fromLatLngZoom(latLng, (float) 14.0);


        SupportMapFragment fragment = SupportMapFragment.newInstance(options);
                .add(, fragment).commit(); 

Also, I have a list of lat/long values. I want to show them on MapFragment, how to show multiple markers on MapFragment?

I tried with MapView and ItemizedOverlay, but it didn’t work for me. I believe I have correctly created the SHA1 key to get the API key, because if that was wrong, I could not see map using MapFragment as well, but I can see that if I don’t pass the lat/log value.

How to solve:

I do it like this to show car positions on the map with markers of different colors:

    private void addMarkersToMap() {
    for (int i = 0; i < Cars.size(); i++) {         
            LatLng ll = new LatLng(Cars.get(i).getPos().getLat(), Cars.get(i).getPos().getLon());
            BitmapDescriptor bitmapMarker;
            switch (Cars.get(i).getState()) {
            case 0:
                bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
                Log.i(TAG, "RED");
            case 1:
                bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN);
                Log.i(TAG, "GREEN");
            case 2:
                bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE);
                Log.i(TAG, "ORANGE");
                bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
                Log.i(TAG, "DEFAULT");
            mMarkers.add(mMap.addMarker(new MarkerOptions().position(ll).title(Cars.get(i).getName())

            Log.i(TAG,"Car number "+i+"  was added " +mMarkers.get(mMarkers.size()-1).getId());


Cars is an ArrayList of custom objects and mMarkers is an ArrayList of markers.

Note : You can show map in fragment like this:

private GoogleMap mMap;

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the
    // map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(;
        // Check if we were successful in obtaining the map.
        if (mMap != null) {

private void setUpMap() {
    // Hide the zoom controls as the button panel will cover it.

    // Add lots of markers to the map.

    // Setting an info window adapter allows us to change the both the
    // contents and look of the
    // info window.
    mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());

    // Set listeners for marker events. See the bottom of this class for
    // their behavior.

    // Pan to see all markers in view.
    // Cannot zoom to bounds until the map has a size.
    final View mapView = getSupportFragmentManager().findFragmentById(;
    if (mapView.getViewTreeObserver().isAlive()) {
        mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            // We check which build version we are using.
            public void onGlobalLayout() {
                LatLngBounds.Builder bld = new LatLngBounds.Builder();
    for (int i = 0; i < mAvailableCars.size(); i++) {           
            LatLng ll = new LatLng(Cars.get(i).getPos().getLat(), Cars.get(i).getPos().getLon());
    LatLngBounds bounds =;          
    mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 70));


And just call setUpMapIfNeeded() in onCreate()


To add multiple markers to map while converting address (ie. 123 Testing Street Lodi ca) to LatLng using geoCoder, the example code below will work.

// convert address to lng lat and add markers to map
public void addMarkersToMap() {
    Double[] latitude = new Double[addressArrayList.size()];
    Double[] longitude = new Double[addressArrayList.size()];
    String[] addrs = new String[addressArrayList.size()];
    addrs = addressArrayList.toArray(addrs);
    List<Address> addressList;
    if (addrs != null && addrs.length > 0) {
        for (int i = 0; i < addrs.length; i++) {
            try {
                addressList = geoCoder.getFromLocationName(addrs[i], 1);
                if (addressList == null || addressList.isEmpty() || addressList.equals("")) {
                    addressList = geoCoder.getFromLocationName("san francisco", 1);
                latitude[i] = addressList.get(0).getLatitude();
                longitude[i] = addressList.get(0).getLongitude();
                System.out.println("latitude = " + latitude[i] + " longitude = " + longitude[i]);
                mMap.addMarker(new MarkerOptions()
                          .position(new LatLng(latitude[i], longitude[i]))
            } catch (Exception e) {
            } // end catch
} //end addMarkersToMap


I don’t know maybe u fixed the code and now it’s ok, but in the onCreate()

if (getIntent().getExtras() != null) {
   final Bundle bundle = getIntent().getBundleExtra("LOCATION");
   mLatitude = bundle.getDouble("LATITUDE");
   mLatitude = bundle.getDouble("LONGITUDE");

the second mLatitude I think it has to be mLongitude just like u call it in the next rows.

Sorry if I’m late with the answer and is useless.


Try this code which calls to an xml file in you web site root directory –

One way to add markers is by loading an xml file that resides on the root directory(see code below), which contains the marker html.

The code here sets up map space and a side-bar column to hold the map and links for the markers. Note that both a div tag with an id and a side-bar td id for the html and map items.

You can set up the markers, but note the need to use special characters that must be tagged correctly; for example ampersand (&) should actually be coded as “&” + “amp” + “;” (without quotes). The same applies to greater than and less than characters, and so on. It is a chore if you have several markers, but once in place it’s easy to change as it doesn’t require any assemblies needing to be built or coding inside the app. In the script which reads the file, using the CDATA tag technically should make the use of special character representation unnecessary, but for Gmaps API v2, I use them anyway. For my example the xml file name is example3.xml.

You can format the xml like this:

<marker lat="47.881389" lng="-122.242222"
html='&lt;div style="background-color:#FFFF88;font-family:Tahoma; font-size:12px;padding:6px;  border:solid 1px black;"&gt;&lt;b&gt;SiteLines Park & Playground Products&lt;/b&gt; &lt;br&gt;626 128th Street SW&lt;br&gt;Suite 104-A&lt;br&gt;Everett‚ WA 98204&lt;br&gt;Phone: (425) 355-5655&lt;br&gt;&lt;b&gt;Toll Free: (800) 541-0869&lt;/b&gt;&lt;br&gt;Fax: (425) 347-3056&lt;br&gt;Email: &lt;a href="" target="blank"&gt;;/a&gt;&lt;br&gt;Web: &lt;a href="" target="blank"&gt;;/a&gt; &lt;/div&gt;'label="SiteLines Park & Playground Products" />

And for the html and script:
<form style="background-color: #ffffff;" id="form1" runat="server">
<div style="text-align: center;">
<table style="border: 1px currentColor; vertical-align: middle;">
<td style="background-color: #bbcae3; vertical-align: top;">
<div style="background-color: #e4e4e4; font-family: Tahoma; font-size: 12px; line-height: 22px;  padding: 5px; text-decoration: underline; width: 210px; color: #000000; text-align: left;" id="side_bar"></div>
<div style="height: 600px; width: 600px;" id="map"></div>
<script type="text/javascript" src=";v=2&amp;key=ABQIAAAAyUoL7QQqyBn6qU653XJGLxSjEdRKL8ahnZ9z8zIKzjlyzNOP2RRCsKP_vlAEzWT8jzEKS0_9RrXOAg"></script>
<script type="text/javascript">// <![CDATA[
if (GBrowserIsCompatible()) {
        // this variable will collect the html which will eventualy be placed in the side_bar
        var side_bar_html = "";

        // arrays to hold copies of the markers and html used by the side_bar
        // because the function closure trick doesnt work there
        var gmarkers = [];
        var htmls = [];
        var i = 0;

        // A function to create the marker and set up the event window
        function createMarker(point, name, html) {
            var marker = new GMarker(point);
            GEvent.addListener(marker, "click", function() {

            // save the info we need to use later for the side_bar
            gmarkers[i] = marker;
            htmls[i] = html;
            // add a line to the side_bar html
            side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
            return marker;

        // This function picks up the click and opens the corresponding info window
        function myclick(i) {

        // create the map
        var map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(0, 0), 0);
        // ===== Start with an empty GLatLngBounds object =====
        var bounds = new GLatLngBounds();

        // Read the data from example3.xml
        GDownloadUrl("/testStore/example3.xml", function(doc) {
            var xmlDoc = GXml.parse(doc);
            var markers = xmlDoc.documentElement.getElementsByTagName("marker");

            for (var i = 0; i < markers.length; i++) {
                // obtain the attribues of each marker
                var lat = parseFloat(markers[i].getAttribute("lat"));
                var lng = parseFloat(markers[i].getAttribute("lng"));
                var point = new GLatLng(lat, lng);
                var html = markers[i].getAttribute("html");
                var label = markers[i].getAttribute("label");
                // create the marker
                var marker = createMarker(point, label, html);
            // put the assembled side_bar_html contents into the side_bar div
            document.getElementById("side_bar").innerHTML = side_bar_html;

    else {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    // This Javascript is based on code provided by the
    // Blackpool Community Church Javascript Team

// ]]>


first craete Method setupDestationLocation

 public void setupDestationLocation(double longlat, double latitue, String title) {
          LatLng Shop = new LatLng(longlat, latitue);
   /* if (DestinationMarker != null) {
    DestinationMarker = mMap.addMarker(new MarkerOptions()
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(Shop, 14);


Now Just call in method inside method (onMapReady)

String title = "market";
    for(int i = 0 ; i < 8 ; i++ ) {
      double offset = i / 08d;



You could try this:

public double getDistanceinKm(double lat1, double long1, double lat2, double long2) {

    Location startPoint = new Location("locationA");

    Location endPoint = new Location("locationA");

    double distanceInKiloMeters = startPoint.distanceTo(endPoint) / 1000;

    return distanceInKiloMeters;

Leave a Reply

Your email address will not be published. Required fields are marked *