这一个要介绍的是在MapActivity上添加图钉。在Android的SDK中有详细的介绍,见以下内容。

Google Map View

Using the Google Maps library, you can create your own map-viewing Activity. In this tutorial, you'll create a simple map application in two parts. In Part 1, you'll create an app that shows a map the user can pan and zoom. In Part 2, you'll add overlay items that mark points of interest.

This tutorial requires that you have the external Google Maps library installed in your SDK environment. The Maps library is included with the Google APIs add-on, which you can install using the Android SDK and AVD Manager. To learn how, seeAdding SDK Components.

After installing the Google APIs add-on in your SDK, set your project properties to use the build target called "Google APIs by Google Inc.". See the instructions for setting a build target inCreating and Managing Projects in EclipseorCreating and Managing Projects on the Command Line, as appropriate for your environment.

You will also need to set up a new AVD that uses the same Google APIs deployment target. SeeCreating and Managing Virtual Devicesfor more information.

For reference material, see theGoogle Maps library documentation.

Part 1: Creating a Map Activity

  1. Start a new project namedHelloGoogleMaps.
  2. Because the Maps library is not a part of the standard Android library, you must declare it in the Android Manifest. Open theAndroidManifest.xmlfile and add the following as a child of the<application>element:
    <uses-libraryandroid:name="com.google.android.maps"/>
  3. You also need access to the Internet in order to retrieve map tiles, so you must also request theINTERNETpermission. In the manifest file, add the following as a child of the<manifest>element:
    <uses-permissionandroid:name="android.permission.INTERNET"/>
  4. While you're in the manifest, give the map some more space by getting rid of the title bar with the "NoTitleBar" theme:
    <activityandroid:name=".HelloGoogleMaps"android:label="@string/app_name"
    android:theme="@android:style/Theme.NoTitleBar">
  5. Open theres/layout/main.xmlfile and add a singlecom.google.android.maps.MapViewas the root node:
    <?xml version="1.0" encoding="utf-8"?>
    <com.google.android.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="Your Maps API Key goes here"
    />

    Theandroid:clickableattribute defines whether you want to allow user-interaction with the map. If this is "false" then touching the map does nothing.

    Theandroid:apiKeyattribute holds the Maps API Key for your application, which proves your application and signer certificate has been registered with the Maps service. This is required in order to receive the map data, even while you are developing. Registration to the service is free and it only takes a couple minutes to register your certificate and get a Maps API Key.

    Go now to get a key. For instructions, readObtaining a Maps API Key. For the purpose of this tutorial, you shouldregister with the SDK debug certificate, which will only be valid while your application is signed with the debug key (once you sign with your private key, you will need a new API key). When you get your key, insert it for the value ofandroid:apiKey.

  6. Now open theHelloGoogleMaps.javafile. For this Activity, extendMapActivity(instead ofandroid.app.Activity):

    publicclassHelloGoogleMapsextendsMapActivity{

    This is a special sub-class ofActivity, provided by the Maps library, which provides important map capabilities.

  7. Inside everyMapActivity, theisRouteDisplayed()method is required, so override this method:
    @Override
    protectedboolean isRouteDisplayed(){
    returnfalse;
    }

    This method is required for some accounting from the Maps service to see if you're currently displaying any route information. In this case, you're not, so return false.

  8. Now add the standardonCreate()callback method to the class:
    @Override
    publicvoid onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView
    (R.layout.main);
    }

    This loads the layout file created above. In fact, this is now a workable application that will display map tiles and allow the user to pan around the map. But there's no ability to zoom. Fortunately, there's a very simple zoom feature built into theMapViewclass, which you can summon withsetBuiltInZoomControls(boolean). Do this at the end of theonCreate()method:

      MapView mapView =(MapView) findViewById(R.id.mapview);
    mapView
    .setBuiltInZoomControls(true);
  9. That's all there is to it. Run the application. (Remember, you must have anAVDconfigured to use the Google APIs target, or be using a development device that includes the Maps library.)

Part 2: Adding Overlay Items

So, now you have a map, but in many cases you'll also want to create your own map markers and lay-overs. That's what you'll do now. In order to do so, you must implement theItemizedOverlayclass, which can manage a whole set ofOverlay(which are the individual items placed on the map).

  1. Create a new Java class namedHelloItemizedOverlaythat implementsItemizedOverlay.

    When using Eclipse, right-click the package name in the Eclipse Package Explorer, and selectNew > Class. Fill-in the Name field asHelloItemizedOverlay. For the Superclass, enter "com.google.android.maps.ItemizedOverlay". Click the checkbox forConstructors from superclass. Click Finish.

  2. First, you need anOverlayItemArrayList, in which you'll put each of theOverlayItemobjects you want on the map. Add this at the top of theHelloItemizedOverlayclass:
    privateArrayList<OverlayItem> mOverlays =newArrayList<OverlayItem>();
  3. Now define theHelloItemizedOverlayconstructors. The constructor must define the default marker for each of theOverlayItems. In order for theDrawableto actually get drawn, it must have its bounds defined. Most commonly, you want the center-point at the bottom of the image to be the point at which it's attached to the map coordinates. This is handled for you with theboundCenterBottom()method. Wrap this around our defaultMarker, so the super constructor call looks like this:
    publicHelloItemizedOverlay(Drawable defaultMarker){
    super(boundCenterBottom(defaultMarker));
    }
  4. In order to add newOverlayItems to the ArrayList, you need a new method:
    publicvoid addOverlay(OverlayItem overlay){
    mOverlays
    .add(overlay);
    populate
    ();
    }

    Each time you add a newOverlayItemto the ArrayList, you must callpopulate()for theItemizedOverlay, which will read each of theOverlayItems and prepare them to be drawn.

  5. When thepopulate()method executes, it will callcreateItem(int)in theItemizedOverlayto retrieve eachOverlayItem. You must override this method to properly read from the ArrayList and return theOverlayItemfrom the position specified by the given integer. Your override method should look like this:
    @Override
    protectedOverlayItem createItem(int i){
    return mOverlays.get(i);
    }
  6. You must also override thesize()method to return the current number of items in the ArrayList:
    @Override
    publicint size(){
    return mOverlays.size();
    }
  7. Now set up the ability to handle touch events on the overlay items. First, you're going to need a reference to the applicationContextas a member of this class. So addContext mContextas a class member, then initialize it with a new class constructor:
    publicHelloItemizedOverlay(Drawable defaultMarker,Context context){
    super(defaultMarker);
    mContext
    = context;
    }

    This passes thedefaultMarkerup to the default constructor to bound its coordinates and then initializemContextwith the givenContext.

    Then override theonTap(int)callback method, which will handle the event when an item is tapped by the user:

    @Override
    protectedboolean onTap(int index){
    OverlayItem item = mOverlays.get(index);
    AlertDialog.Builder dialog =newAlertDialog.Builder(mContext);
    dialog
    .setTitle(item.getTitle());
    dialog
    .setMessage(item.getSnippet());
    dialog
    .show();
    returntrue;
    }

    This uses the memberandroid.content.Contextto create a newAlertDialog.Builderand uses the tappedOverlayItem's title and snippet for the dialog's title and message text. (You'll see theOverlayItemtitle and snippet defined when you create it below.)

You're now done with theHelloItemizedOverlayclass and can start using it to add items on the map.

Go back to theHelloGoogleMapsclass. In the following procedure, you'll create anOverlayItemand add it to an instance of theHelloItemizedOverlayclass, then add theHelloItemizedOverlayto theMapViewusing aGeoPointto define its coordinates on the map.

  1. First, you need the image for the map overlay. If you don't have one handy, use the Android on the right. Drag this image (or your own) into theres/drawable/directory of your project.
  2. At the end of your existingonCreate()method, instantiate :
    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable =this.getResources().getDrawable(R.drawable.androidmarker);
    HelloItemizedOverlay itemizedoverlay =newHelloItemizedOverlay(drawable,this);

    All overlay elements on a map are held by theMapView, so when you want to add some, you have to get a list from thegetOverlays()method. Then instantiate theDrawableused for the map marker, which was saved in theres/drawable/directory. The constructor forHelloItemizedOverlay(your customItemizedOverlay) takes the Drawable in order to set the default marker for all overlay items.

  3. Now create aGeoPointthat defines the map coordinates for the first overlay item, and pass it to a newOverlayItem:
    GeoPoint point =newGeoPoint(19240000,-99120000);
    OverlayItem overlayitem =newOverlayItem(point,"Hola, Mundo!","I'm in Mexico City!");

    GeoPointcoordinates are specified in microdegrees (degrees * 1e6). TheOverlayItemconstructor accepts theGeoPointlocation, a string for the item's title, and a string for the item's snippet text, respectively.

  4. All that's left is to add thisOverlayItemto your collection in theHelloItemizedOverlayinstance, then add theHelloItemizedOverlayto the MapView:
    itemizedoverlay.addOverlay(overlayitem);
    mapOverlays
    .add(itemizedoverlay);
  5. Now run the application.

You should see the following:

When you tap the overlay item, you'll see the dialog appear.

Because theItemizedOverlayclass uses anjava.util.ArrayListfor all of theOverlayItems, it's easy to add more. Try adding another one. Before theaddOverlay()method is called, add these lines:

GeoPoint point2 =newGeoPoint(35410000,139460000);
OverlayItem overlayitem2 =newOverlayItem(point2,"Sekai, konichiwa!","I'm in Japan!");

Run the application again. (You probably need to move the map to find the new overlay item.)

更多相关文章

  1. Android(安卓)display架构分析四-msm_fb.c 函数和数据结构介绍
  2. Okhttp的简单介绍和使用(一)
  3. Android(安卓)JNI 开发简单介绍
  4. Android(安卓)Query框架用法简单介绍
  5. AndroidStudio中导入module详细介绍
  6. android webview 介绍
  7. [置顶] 我的Android进阶之旅------>Android常用计量单位(Dimensio
  8. Android之旅 -- ARouter 使用介绍(一)
  9. 应用程序Manifest介绍

随机推荐

  1. android UI进阶之android中隐藏的layout
  2. Android和设计模式:备忘录模式
  3. Android(安卓)无障碍服务一 让应用具有辅
  4. Android无线连接打印第三方开发的实现
  5. Android之如何学习
  6. Android(安卓)APK 签名比对,防止软件被破
  7. UWP与Android中如何在多线程中刷新UI
  8. 【Android休眠】之Android休眠机制
  9. android 内部文件读取
  10. 2016年10月Android岗校招笔试面试总结