1

I have made a very simple demo program for android map view (api v2) by referring the following link,But my program doesn't shows map.its not running.Please help me,My code is as below:

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

main.java

    package com.example.mymap;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.support.v4.app.FragmentActivity; 

public class MainActivity extends FragmentActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }



}

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mymap"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>


    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <permission
        android:name="com.example.mymap.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <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="com.example.mymap.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mymap.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>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCuS-daQYgOZsmbIBYUTCl0P5tV0GTnjrI" />
    </application>

</manifest>
Valery Viktorovsky
  • 6,487
  • 3
  • 39
  • 47
jigar
  • 1,571
  • 6
  • 23
  • 46

5 Answers5

4

Please try to use my running code.

Firstly import Google play service library project from /Android/android-sdk-linux/extras/google/google_play_services and after that create new project and write this code.

//Main Activity
package in.wptrafficanalyzer.multipleproximitymapv2;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {

GoogleMap googleMap;
LocationManager locationManager;
PendingIntent pendingIntent;
SharedPreferences sharedPreferences;
int locationCount = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are
                                                // not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service
        // LOCATION_SERVICE
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Opening the sharedPreferences object
        sharedPreferences = getSharedPreferences("location", 0);

        // Getting number of locations already stored
        locationCount = sharedPreferences.getInt("locationCount", 0);

        // Getting stored zoom level if exists else return 0
        String zoom = sharedPreferences.getString("zoom", "0");

        // If locations are already saved
        if (locationCount != 0) {

            String lat = "";
            String lng = "";

            // Iterating through all the locations stored
            for (int i = 0; i < locationCount; i++) {

                // Getting the latitude of the i-th location
                lat = sharedPreferences.getString("lat" + i, "0");

                // Getting the longitude of the i-th location
                lng = sharedPreferences.getString("lng" + i, "0");

                // Drawing marker on the map
                drawMarker(new LatLng(Double.parseDouble(lat),
                        Double.parseDouble(lng)));

                // Drawing circle on the map
                drawCircle(new LatLng(Double.parseDouble(lat),
                        Double.parseDouble(lng)));
            }

            // Moving CameraPosition to last clicked position
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
                    Double.parseDouble(lat), Double.parseDouble(lng))));

            // Setting the zoom level in the map on last position is clicked
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float
                    .parseFloat(zoom)));
        }

        googleMap.setOnMapClickListener(new OnMapClickListener() {

            public void onMapClick(LatLng point) {

                // Incrementing location count
                locationCount++;

                // Drawing marker on the map
                drawMarker(point);

                // Drawing circle on the map
                drawCircle(point);

                // This intent will call the activity ProximityActivity
                Intent proximityIntent = new Intent(
                        "in.wptrafficanalyzer.activity.proximity");

                // Passing latitude to the PendingActivity
                proximityIntent.putExtra("lat", point.latitude);

                // Passing longitude to the PendingActivity
                proximityIntent.putExtra("lng", point.longitude);

                // Creating a pending intent which will be invoked by
                // LocationManager when the specified region is
                // entered or exited
                pendingIntent = PendingIntent.getActivity(getBaseContext(),
                        0, proximityIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

                // Setting proximity alert
                // The pending intent will be invoked when the device enters
                // or exits the region 20 meters
                // away from the marked point
                // The -1 indicates that, the monitor will not be expired
                locationManager.addProximityAlert(point.latitude,
                        point.longitude, 20, -1, pendingIntent);

                /**
                 * Opening the editor object to write data to
                 * sharedPreferences
                 */
                SharedPreferences.Editor editor = sharedPreferences.edit();

                // Storing the latitude for the i-th location
                editor.putString(
                        "lat" + Integer.toString((locationCount - 1)),
                        Double.toString(point.latitude));

                // Storing the longitude for the i-th location
                editor.putString(
                        "lng" + Integer.toString((locationCount - 1)),
                        Double.toString(point.longitude));

                // Storing the count of locations or marker count
                editor.putInt("locationCount", locationCount);

                /** Storing the zoom level to the shared preferences */
                editor.putString("zoom",
                        Float.toString(googleMap.getCameraPosition().zoom));

                /** Saving the values stored in the shared preferences */
                editor.commit();

                Toast.makeText(getBaseContext(),
                        "Proximity Alert is added", Toast.LENGTH_SHORT)
                        .show();

            }
        });

        googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {

            public void onMapLongClick(LatLng point) {
                Intent proximityIntent = new Intent(
                        "in.wptrafficanalyzer.activity.proximity");

                pendingIntent = PendingIntent.getActivity(getBaseContext(),
                        0, proximityIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

                // Removing the proximity alert
                locationManager.removeProximityAlert(pendingIntent);

                // Removing the marker and circle from the Google Map
                googleMap.clear();

                // Opening the editor object to delete data from
                // sharedPreferences
                SharedPreferences.Editor editor = sharedPreferences.edit();

                // Clearing the editor
                editor.clear();

                // Committing the changes
                editor.commit();

                Toast.makeText(getBaseContext(),
                        "Proximity Alert is removed", Toast.LENGTH_LONG)
                        .show();
            }
        });
    }
}

private void drawCircle(LatLng point) {

    // Instantiating CircleOptions to draw a circle around the marker
    CircleOptions circleOptions = new CircleOptions();

    // Specifying the center of the circle
    circleOptions.center(point);

    // Radius of the circle
    circleOptions.radius(20);

    // Border color of the circle
    circleOptions.strokeColor(Color.BLACK);

    // Fill color of the circle
    circleOptions.fillColor(0x30ff0000);

    // Border width of the circle
    circleOptions.strokeWidth(2);

    // Adding the circle to the GoogleMap
    googleMap.addCircle(circleOptions);

}

private void drawMarker(LatLng point) {
    // Creating an instance of MarkerOptions
    MarkerOptions markerOptions = new MarkerOptions();

    // Setting latitude and longitude for the marker
    markerOptions.position(point);

    // Adding InfoWindow title
    markerOptions.title("Location Coordinates");

    // Adding InfoWindow contents
    markerOptions.snippet(Double.toString(point.latitude) + ","
            + Double.toString(point.longitude));

    // Adding marker on the Google Map
    googleMap.addMarker(markerOptions);
}
}

// activity_main

<fragment
    android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />


//Manifiest

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<permission
    android:name="in.wptrafficanalyzer.multipleproximitymapv2.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="in.wptrafficanalyzer.multipleproximitymapv2.permission.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" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="in.wptrafficanalyzer.multipleproximitymapv2.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>
    <activity
        android:name=".ProximityActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="in.wptrafficanalyzer.activity.proximity" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NotificationView"
        android:label="@string/app_name" >
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyD2fSGTakDlROXxr2IJeDH6f31b7BSc0F8" />
</application>

Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
nilesh patel
  • 834
  • 1
  • 5
  • 10
  • 9
    you have posted your app code instead of pointing out at mistakes in op's code and your app map key. – Raghunandan Jul 04 '13 at 12:16
  • https://developers.google.com/maps/documentation/android/start...I have used the above link...is it possible this way?i have followed the mentioned steps but not working...! – jigar Jul 04 '13 at 12:18
1

Add library to your AndroidManifest File:

  <uses-library
        android:name="com.google.android.maps"
        android:required="true" />
Shani Goriwal
  • 2,111
  • 1
  • 18
  • 30
  • @Shani-still same thing happened ...! – jigar Jul 04 '13 at 12:10
  • So have you add library project for that? And have you installed google play library from Android SDK?? – Shani Goriwal Jul 04 '13 at 12:12
  • but https://developers.google.com/maps/documentation/android/start link doesnt ahow such step...! – jigar Jul 04 '13 at 12:38
  • @jigar did you check the links in my comment it does point you to the steps mentioned. Look at the docs closely. Check my commnent where the first link shows you how to download and setup. the second link points you the steps. Check the first step in the overview. It does ask you to setup google play services. **Download and configure the Google Play services SDK** – Raghunandan Jul 04 '13 at 12:39
  • You have to first install google library project from android sdk and then import it to eclipse and add as a library project to your project – Shani Goriwal Jul 04 '13 at 12:40
  • @ShaniGoriwal I really don't know but do you realize that the mods deleted some of your answers because you do "double answers"? Here again: Please stop creating more than one answer for a question! SO works different! Update your first answer to reflect changes or improvements but do NOT create a second or third answer on the same question! – WarrenFaith Jul 04 '13 at 16:00
1

Just check this:

package com.example.mymap;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.support.v4.app.FragmentActivity; 

public class MainActivity extends FragmentActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    FragmentManager myFM = .getSupportFragmentManager();

    SupportMapFragment myMAPF = (SupportMapFragment) myFM
            .findFragmentById(R.id.fragment1);
    MAP = myMAPF.getMap();
    MAP.setMyLocationEnabled(true);
    MAP.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    MAP.setOnMapClickListener(new OnMapClickListener() {
        @Override
        public void onMapClick(LatLng point) {
            // TODO Auto-generated method stub
            MAP.addMarker(new MarkerOptions().position(point).title(
                    point.toString()));
            Log.e("lat", "" + point);
        }
    });

}

}

Your xml file will be:

              <fragment
                android:id="@+id/fragment1"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:layout_below="@+id/fragment1"
                android:layout_centerHorizontal="true"
                class="com.google.android.gms.maps.SupportMapFragment" />    

And finally add libray in manifest file:

 <uses-library
    android:name="com.google.android.maps"
    android:required="true" />
Shani Goriwal
  • 2,111
  • 1
  • 18
  • 30
  • https://developers.google.com/maps/documentation/android/start. No need for `used-library`. – Raghunandan Jul 04 '13 at 12:14
  • @jigar have you referenced library project in your map project? You have not mentioned the same. I guess you have not. see my edit in the answer. Also make sure you have enables maps for android in google api console. – Raghunandan Jul 04 '13 at 12:20
  • I have gone thru the same link...and followed same steps from the same link...dats not working...dats y i have posted this question....! – jigar Jul 04 '13 at 12:44
0

You should use SupportFragment Your min sdk is 8.

<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map"  
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Your activity must extend FragmentActivity

Import

import android.support.v4.app.FragmentActivity;  
import com.google.android.gms.maps.SupportMapFragment; 

Edit:

From your comments you say there is a error @

    import com.google.android.gms.maps.SupportMapFragment;

So i guess you have not referenced google play services library project properly.

Download the Google Play services. Goto Windows. Goto Android Sdk Manager. Choose Google play services under extras.

Copy the google-play services_lib library project to your workspace. The library project can be found under the following path.

     <android-sdk-folder>/extras/google/google_play_services/libproject/google-play-services_lib library project .

Import the library project to your eclipse

Click File > Import, select Android > Existing Android Code into Workspace, and browse the workspace import the library project. You can check if it is library project. Right click on the library project. Goto properties. Click Android on the left panel. You will see Is Library checked.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • @jigar what do you mean by its not working?. Do you get exceptions or errors? – Raghunandan Jul 04 '13 at 12:04
  • @jigar you are still using MapFragment in your xml – Raghunandan Jul 04 '13 at 12:05
  • import com.google.android.gms.maps.SupportMapFragment; displayes error line...! and my emulator shows your app unfortunately not runnig – jigar Jul 04 '13 at 12:07
  • @jigar have you referenced the library project in your android project. I guess you have not done that – Raghunandan Jul 04 '13 at 12:07
  • Library project? for api v2? – jigar Jul 04 '13 at 12:20
  • i followed the steps but not working...dats y posted question..! :o – jigar Jul 04 '13 at 12:22
  • @jigar check this link http://developer.android.com/google/play-services/setup.html. you have not followed all the steps mentioned in the link. The first step in the overview @ https://developers.google.com/maps/documentation/android/start says **Download and configure the Google Play services SDK. The Google Maps Android API is distributed as part of this SDK**. – Raghunandan Jul 04 '13 at 12:23
  • @jigar you should also test your app on a real device. Although you can test it on emulator with a work around suggest you to test it on device. – Raghunandan Jul 04 '13 at 12:27
0

Try this.

In your xml file

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      class="com.google.android.gms.maps.SupportMapFragment"/>

In the java file

public class MapExampleActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map_example);

    //setUpMap
}
android developer
  • 1,253
  • 2
  • 13
  • 43