`
zhouxin464585932
  • 浏览: 78244 次
  • 性别: Icon_minigender_1
  • 来自: 南京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

android mapview

阅读更多

转载地图的使用

http://wang-peng1.iteye.com/blog/607197

文章分类:移动开发





http://mobiforge.com/developing/story/using-google-maps-android

Google Maps is one of the many applications bundled with the Android platform. In addition to simply using the Maps application, you can also embed it into your own applications and make it do some very cool things. In this article, I will show you how to use Google Maps in your Android applications and how to programmatically perform the following:

  1. Change the views of Google Maps
  2. Obtain the latitude and longitude of locations in Google Maps
  3. Perform geocoding and reverse geocoding
  4. Add markers to Google Maps

Creating the Project

Using Eclipse, create a new Android project and name GoogleMaps as shown in Figure 1.




Figure 1 Creating a new Android project using Eclipse

Obtaining a Maps API key

Beginning with the Android SDK release v1.0, you need to apply for a free Google Maps API key before you can integrate Google Maps into your Android application. To apply for a key, you need to follow the series of steps outlined below. You can also refer to Google's detailed documentation on the process at http://code.google.com/android/toolbox/apis/mapkey.html.

First, if you are testing the application on the Android emulator, locate the SDK debug certificate located in the default folder of "C:\Documents and Settings\<username>\Local Settings\Application Data\Android". The filename of the debug keystore is debug.keystore. For deploying to a real Android device, substitute the debug.keystore file with your own keystore file. In a future article I will discuss how you can generate your own keystore file.

For simplicity, copy this file (debug.keystore) to a folder in C:\ (for example, create a folder called "C:\Android").

Using the debug keystore, you need to extract its MD5 fingerprint using the Keytool.exe application included with your JDK installation. This fingerprint is needed to apply for the free Google Maps key. You can usually find the Keytool.exe from the "C:\Program Files\Java\<JDK_version_number>\bin" folder.

Issue the following command (see also Figure 2) to extract the MD5 fingerprint.

keytool.exe -list -alias androiddebugkey -keystore "C:\android\debug.keystore" -storepass android -keypass android

Copy the MD5 certificate fingerprint and navigate your web browser to: http://code.google.com/android/maps-api-signup.html. Follow the instructions on the page to complete the application and obtain the Google Maps key.




Figure 2 Obtaining the MD5 fingerprint of the debug keystore

To use the Google Maps in your Android application, you need to modify your AndroidManifest.xml file by adding the <uses-library> element together with the INTERNET permission:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.GoogleMaps"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">

    <uses-library android:name="com.google.android.maps" />  

        <activity android:name=".MapsActivity"
                  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>

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

</manifest>
</xml>

Displaying the Map

To display the Google Maps in your Android application, modify the main.xml file located in the res/layout folder. You shall use the <com.google.android.maps.MapView> element to display the Google Maps in your activity. In addition, let's use the <RelativeLayout> element to position the map within the activity:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">

    <com.google.android.maps.MapView 
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="0l4sCTTyRmXTNo7k8DREHvEaLar2UmHGwnhZVHQ"
        />

</RelativeLayout>

Notice from above that I have used the Google Maps key that I obtained earlier and put it into the apiKey attribute.

In the MapsActivity.java file, modify the class to extend from the MapActivity class, instead of the normal Activity class:

package net.learn2develop.GoogleMaps;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.os.Bundle;

public class MapsActivity extends MapActivity 
{    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

Observe that if your class extends the MapActivity class, you need to override the isRouteDisplayed() method. You can simply do so by setting the method to return false.

That's it! That's all you need to do to display the Google Maps in your application. Press F11 in Eclipse to deploy the application onto an Android emulator. Figure 3 shows the Google map in all its glory.




Figure 3 Google Maps in your application

At this juncture, take note of a few troubleshooting details. If your program does not run (i.e. it crashes), then it is likely you forgot to put the following statement in your AndroidManifest.xml file:

    <uses-library android:name="com.google.android.maps" />

If your application manages to load but you cannot see the map (all you see is a grid), then it is very likely you do not have a valid Map key, or that you did not specify the INTERNET permission:

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

Displaying the Zoom View

The previous section showed how you can display the Google Maps in your Android device. You can drag the map to any desired location and it will be updated on the fly. However, observe that there is no way to zoom in or out from a particular location. Thus, in this section, you will learn how you can let users zoom into or out of the map.

First, add a <LinearLayout> element to the main.xml file as shown below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">

    <com.google.android.maps.MapView 
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="0l4sCTTyRmXTNo7k8DREHvEaLar2UmHGwnhZVHQ"
        />

    <LinearLayout android:id="@+id/zoom" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignParentBottom="true" 
        android:layout_centerHorizontal="true" 
        /> 

</RelativeLayout>

You will use the <LinearLayout> element to hold the two zoom controls in Google Maps (you will see this shortly).

In the MapsActivity.java file, add the following imports:

import com.google.android.maps.MapView.LayoutParams;  
import android.view.View;
import android.widget.LinearLayout;

and add the following code after the line setContentView(R.layout.main);

        mapView = (MapView) findViewById(R.id.mapView);
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
        View zoomView = mapView.getZoomControls(); 

        zoomLayout.addView(zoomView, 
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT)); 
        mapView.displayZoomControls(true);

The complete MapsActivity.java file is given below:

package net.learn2develop.GoogleMaps;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;  

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

public class MapsActivity extends MapActivity 
{    
    MapView mapView; 

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        mapView = (MapView) findViewById(R.id.mapView);
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
        View zoomView = mapView.getZoomControls(); 

        zoomLayout.addView(zoomView, 
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT)); 
        mapView.displayZoomControls(true);

    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}

Basically, you obtain the MapView instance on the activity, obtain its zoom controls and then add it to the LinearLayout element you added to the activity earlier on. In the above case, the zoom control will be displayed at the bottom of the screen. When you now press F11 in Eclipse, you will see the zoom controls when you touch the map (see Figure 4).




Figure 4 Using the zoom controls in Google Maps

Using the zoom control, you can zoom in or out of a location by simply touching the "+ or "-" buttons on the screen.

Alternatively, you can also programmatically zoom in or out of the map using the zoomIn() and zoomOut() methods from the MapController class:

package net.learn2develop.GoogleMaps;

//...
import android.os.Bundle;
import android.view.KeyEvent;

public class MapsActivity extends MapActivity 
{    
    MapView mapView; 

    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        MapController mc = mapView.getController(); 
        switch (keyCode) 
        {
            case KeyEvent.KEYCODE_3:
                mc.zoomIn();
                break;
            case KeyEvent.KEYCODE_1:
                mc.zoomOut();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }    

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        //...
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}

In the above code, when the user presses the number 3 on the keyboard the map will zoom in into the next level. Pressing number 1 will zoom out one level.

Changing Views of the Map

By default, the Google Maps displays in the map mode. If you wish to display the map in satellite view, you can use the setSatellite() method of the MapView class, like this:

        mapView.setSatellite(true);

You can also display the map in street view, using the setStreetView() method:

        mapView.setStreetView(true);

Figure 5 shows the Google Maps displayed in satellite and street views, respectively.




Figure 5 Displaying Google Maps in satellite and street views

Displaying a Particular Location

Be default, the Google Maps displays the map of the United States when it is first loaded. However, you can also set the Google Maps to display a particular location. In this case, you can use the animateTo() method of the MapController class.

The following code shows how this is done:

package net.learn2develop.GoogleMaps;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

public class MapsActivity extends MapActivity 
{    
    MapView mapView; 
    MapController mc;
    GeoPoint p;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mapView = (MapView) findViewById(R.id.mapView);
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
        View zoomView = mapView.getZoomControls(); 

        zoomLayout.addView(zoomView, 
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT)); 
        mapView.displayZoomControls(true);

        mc = mapView.getController();
        String coordinates[] = {"1.352566007", "103.78921587"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);

        p = new GeoPoint(
            (int) (lat * 1E6), 
            (int) (lng * 1E6));

        mc.animateTo(p);
        mc.setZoom(17); 
        mapView.invalidate();
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}

In the above code, you first obtain a controller from the MapView instance and assign it to a MapController object (mc). You use a GeoPoint object to represent a geographical location. Note that for this class the latitude and longitude of a location are represented in micro degrees. This means that they are stored as integer values. For a latitude value of 40.747778, you need to multiply it by 1e6 to obtain 40747778.

To navigate the map to a particular location, you can use the animateTo() method of the MapController class (an instance which is obtained from the MapView object). The setZoom() method allows you to specify the zoom level in which the map is displayed. Figure 6 shows the Google Maps displaying the map of Singapore.




Figure 6 Navigating to a particular location on the map

Adding Markers

Very often, you may wish to add markers to the map to indicate places of interests. Let's see how you can do this in Android. First, create a GIF image containing a pushpin (see Figure 7) and copy it into the res/drawable folder of the project. For best effect, you should make the background of the image transparent so that it does not block off parts of the map when the image is added to the map.




Figure 7 Adding an image to the res/drawable folder

To add a marker to the map, you first need to define a class that extends the Overlay class:

package net.learn2develop.GoogleMaps;

import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.MapView.LayoutParams;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

public class MapsActivity extends MapActivity 
{    
    MapView mapView; 
    MapController mc;
    GeoPoint p;

    class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, 
        boolean shadow, long when) 
        {
            super.draw(canvas, mapView, shadow);                   

            //---translate the GeoPoint to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(p, screenPts);

            //---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(
                getResources(), R.drawable.pushpin);            
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);         
            return true;
        }
    } 

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        //...
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}

In the MapOverlay class that you have defined, override the draw() method so that you can draw the pushpin image on the map. In particular, note that you need to translate the geographical location (represented by a GeoPoint object, p) into screen coordinates.

As you want the pointed tip of the push pin to indicate the position of the location, you would need to deduct the height of the image (which is 50 pixels) from the y-coordinate of the point (see Figure 8) and draw the image at that location.




Figure 8 Adding an image to the map

To add the marker, create an instance of the MapOverlap class and add it to the list of overlays available on the MapView object:

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //...

        mc.animateTo(p);
        mc.setZoom(17); 

        //---Add a location marker---
        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);        

        mapView.invalidate();
    }

Figure 9 shows how the pushpin looks like when added to the map.




Figure 9 Adding a marker to the map

Getting the Location that was touched

After using Google Maps for a while, you may wish to know the latitude and longitude of a location corresponding to the position on the screen that you have just touched. Knowing this information is very useful as you can find out the address of a location, a process known as Geocoding (you will see how this is done in the next section).

If you have added an overlay to the map, you can override the onTouchEvent() method within the Overlay class. This method is fired every time the user touches the map. This method has two parameters - MotionEvent and MapView. Using the MotionEvent parameter, you can know if the user has lifted his finger from the screen using the getAction() method. In the following code, if the user has touched and then lifted his finger, you will display the latitude and longitude of the location touched:

    class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, 
        boolean shadow, long when) 
        {
           //...
        }

        @Override
        public boolean onTouchEvent(MotionEvent event, MapView mapView) 
        {   
            //---when user lifts his finger---
            if (event.getAction() == 1) {                
                GeoPoint p = mapView.getProjection().fromPixels(
                    (int) event.getX(),
                    (int) event.getY());
                    Toast.makeText(getBaseContext(), 
                        p.getLatitudeE6() / 1E6 + "," + 
                        p.getLongitudeE6() /1E6 , 
                        Toast.LENGTH_SHORT).show();
            }                            
            return false;
        }        
    }

Figure 10 shows this in action.




Figure 10 Displaying the latitude and longitude of a point touched on the map

Geocoding and Reverse Geocoding

If you know the latitude and longitude of a location, you can find out its address using a process known as Geocoding. Google Maps in Android supports this via the Geocoder class. The following code shows how you can find out the address of a location you have just touched using the getFromLocation() method:

    class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, 
        boolean shadow, long when) 
        {
          //...
        }

        @Override
        public boolean onTouchEvent(MotionEvent event, MapView mapView) 
        {   
            //---when user lifts his finger---
            if (event.getAction() == 1) {                
                GeoPoint p = mapView.getProjection().fromPixels(
                    (int) event.getX(),
                    (int) event.getY());

                Geocoder geoCoder = new Geocoder(
                    getBaseContext(), Locale.getDefault());
                try {
                    List<Address> addresses = geoCoder.getFromLocation(
                        p.getLatitudeE6()  / 1E6, 
                        p.getLongitudeE6() / 1E6, 1);
</di
分享到:
评论

相关推荐

    android mapview

    android 开发中的基础知识 对mapview 的掌握

    Android MapView 应用

    Android MapView 应用,基于Android开发,应用Android SDK 1.5

    Android中MapView的使用方法.pdf

    在Android开发中,`MapView`是用于展示地图的关键组件,它是`com.amap.api.maps.MapView`类的一个实例,源自高德地图API。这个组件允许开发者在应用中集成地图功能,提供用户地理位置信息、导航、定位等服务。下面将...

    android MapView地图测试

    在Android开发中,`MapView`是Google Maps Android API提供的重要组件,它允许开发者在应用程序中嵌入交互式地图。这个`MapView`地图测试是开发者在实际项目中进行地图功能调试和展示的一个常见实践。下面我们将深入...

    在android的mapview上添加浮动按钮的layout

    在android的mapview上添加浮动按钮,并固定在右下角

    Android GoogleMap教程和实例

    文件"获得Google_Map_API_key及android_MapView_实现google地图.docx"很可能包含了详细的步骤,指导开发者如何注册Google Cloud Platform项目,启用Google Maps Android API,并生成用于应用的API密钥。这个过程通常...

    osmdroid+google地图android应用

    osmdroid提供了一个地图视图(MapView)组件,可以替代原生的Android MapView。这个组件能够加载各种地图瓦片源,包括Google Maps瓦片。要使用Google Maps,我们需要在项目中添加对应的依赖,并配置合法的API密钥,...

    Eclipse 开发 Android, Hello, MapView (学习5)

    在本篇博客“Eclipse开发Android,Hello, MapView(学习5)”中,我们将探讨如何在Android开发环境中使用Eclipse集成开发环境(IDE)来创建一个简单的应用程序,该程序展示了一个显示地图的MapView。这个过程涉及到...

    Android信息标注球android-mapviewballoons.zip

    android-mapviewballoons 是用于 Android MapView 上简单的信息标注球。 标签:android

    Android平台室内地图控件MapView.zip

    在Android平台上,开发室内地图应用时,我们常常会用到一个关键的控件——MapView。MapView是Google Maps Android API提供的一种组件,它允许开发者在应用程序中集成地图功能,展示地图数据,实现地图的缩放、平移、...

    Android高仿滴滴打车等软件项目源码

    这需要对Android MapView和MapFragment有深入理解。 3. **路线规划**:滴滴打车应用需要能够根据起始点和目的地计算最优行驶路线,这通常通过调用第三方地图服务的路线规划接口实现,比如Google Directions API。...

    ArcGIS Runtime SDK for Android之mapView方法.doc

    ArcGIS Runtime SDK for Android之MapView方法 MapView 是 ArcGIS Runtime SDK for Android 中的一个核心组件,用于显示和交互地图。它提供了丰富的方法来控制和操作地图的行为。本文档将详细介绍 MapView 中的公有...

    解析Android中View转换为Bitmap及getDrawingCache=null的解决方法

    Android中经常会遇到把View转换为Bitmap的情形,比如,对整个屏幕视图进行截屏并生成图片;Coverflow中需要把一页一页的view转换为Bitmap、以便实现复杂的图形效果(阴影、倒影效果等);再比如一些动态的实时View为...

    android transparent panel on google mapview

    这个"android transparent panel on google mapview"的示例代码正是针对这一需求的实践。透明面板可以让用户透过面板看到下面的地图,同时在面板上可以放置按钮、文本或其他UI元素,实现与地图的互动。 首先,我们...

    gmap气球源码

    在"jgilfelt-android-mapviewballoons-4531597"这个压缩包中,我们可以找到由Jeff Gilfelt开发的开源库,它为Android MapView提供了一个方便的实现,用于展示气球标注。这个库简化了创建带有气球的自定义overlay的...

    GDALAndroid库.zip

    1. 地图数据的读取和显示:加载地理空间数据,如卫星图像或地形图,并在Android MapView上显示。 2. 数据转换:将不同格式的地图数据转换为适合Android平台的格式。 3. 数据处理:对地图数据进行裁剪、缩放、坐标...

    数据库与MapView总结

    MapView是Google Maps Android API的一部分,它允许开发者在Android应用中集成Google地图功能。使用MapView,开发者可以显示地图、添加标记、绘制路径、获取用户位置等。要使用MapView,首先需要在Google Cloud ...

Global site tag (gtag.js) - Google Analytics