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);
在论坛里看到一篇 "MapView和其它控件一起显示 " 的帖子, 那是很老的一篇帖子了, 很多朋友都说无法在android SDK 1.0上运行。既然那么多人关心,我在这里就把它重写一遍,顺便加入了一些新的功能 ,感兴趣的朋友可以看看。 第一步,当然是增加map的支持了。在Android Manifest.xml中增加以下语句: 第二步, 传说中的Layout: 然后, 创建一个MapViewActivity: public class MapViewActivity extends MapActivity { MapView mapView; MapController mapController; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mapView = (MapView) findViewById(R.id.map); mapController = mapView.getController(); mapController.setZoom(15); updateView(); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } private void updateView(){ Double lat = 31.23717*1E6; Double lng = 121.50811*1E6; GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue()); mapController.setCenter(point); } } 好了,你的MapView上面就多了一个EditText了。 接着,我希望在MapView中增加ZoomIn和ZoomOut的功能(鄙视一下Google ,缺省的MapView居然连这个功能都没有) 1. 在我们的Layout中增加一段: 2. 在onCreate函数中增加: ViewGroup zoom=(ViewGroup)findViewById(R.id.zoom); zoom.addView(mapView.getZoomControls()); 现在在你的地图中点一下,屏幕左下角,是不是出现了一个Zoom Table? 这才是一个最基本的地图功能嘛。 以下技巧是基于SDK 1.0的) 一、申请Apikey,并放在正确的位置http://iceskysl.1sters.com/?action=show&id=441 这个应该都知道,但是是申请得到的key放哪里很多人不知道,可以放在 1、XML布局文件中 申请APIkey的时候,类似命令如下: C:\Documents and Settings\Administrator\Local Settings\Application Data\Android> "C:\Program Files\Java\jdk1.6.0_10\bin\keytool.exe" -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android androiddebugkey, 2008-9-23, PrivateKeyEntry, 认证指纹 (MD5): 1D:68:43:7C:14:2E:CC:CA:35:8B:1F:93:A7:91:AD:45 2、java中 mMapView = new MapView(this, "01Yu9W3X3vbpYT3x33chPxxx7U1Z6jy8WYZXNFA"); 二、记得导入uses-library 由于1.0版本的修改,使得map包不再是默认的了,使用的时候需要在manifest中的application节点下加入 否则,你将遇到可恶的“java.lang.NoClassDefFoundError: ”,切记! 三、需要给予一定的权限 因为要使用GoogleMAP的service,所以需要 如果需要GPS等应用,还需要 四、Activity需要继承自MapActivity 类似如下代码; package com.iceskysl.showmap; import com.google.android.maps.MapActivity; import android.os.Bundle; public class ShowMap 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() { // TODO Auto-generated method stub return false; } } 在Android中使用其提供的Sensor非常方便,如下是强制Landscape时候的情况: values[0]:方位角(水平旋转角),简单的说就是手机的头现在朝向哪个方位,0=北、90=东、180=南、270=西(可是好像不太准) values[1]:纵向旋转角,0=面朝上平置、-90=垂直向上、-180/180=面朝下平置、90=垂直向下 values[2]:橫向旋转角,0=朝前、90=往右倒、-90=往左倒 在Android中计算GPS两点间的距离/速度 Q:how to get distance between two GeoPoints in sdk 1.0 ? MapPoint.distanceSquared(MapPoint) is gone thaks!! A:you'll need to brush up on your trigonometry, and first compute the Haversine function (this is the standard way of doing it). In order to use the Java trig functions, you'll have to first convert all your angles from degrees to radians. Given two longitude/latitude pairs, and the earth's average radius (assume 6356.78km for your calculations), you can calculate the distance between the 2 points via this Java code: double EarthRad = 6356.78; // in km ! // first convert to radians... double geo1_lat = geo1.getLatitude()*java.lang.Math.PI/360; double geo1_lng = geo1.getLongitude()*java.lang.Math.PI/360; double geo2_lat = geo2.getLatitude()*java.lang.Math.PI/360; double geo2_lng = geo2.getLongitude()*java.lang.Math.PI/360; double deltaLat = java.lang.Math.abs(java.lang.Math.abs(geo2_lat) - java.lang.Math.abs(geo1_lat)); double deltaLng = java.lang.Math.abs(java.lang.Math.abs(geo2_lng) - java.lang.Math.abs(geo1_lng)); double dist = 2*EarthRad*java.lang.Math.asin(java.lang.Math.sqrt(haversine(deltaLat) + java.lang.Math.cos(pair1_lat) *java.lang.Math.cos(pair1_lng)*haversine(deltaLng))); Where "dist" now contains the distance between along the earth's surface. You can find the Haversine function trig equation by Googling it, then construct a method that returns the appropriate value. Computing the speed is straightforward: you know your sampling frequency, and you now know the distance between the most recent two points, so, employee speed = distance / sampling interval 参考:http://www.anddev.org/distance_between_two_geopoints_in_sdk10-t4195.html http://www.anddev.org/calculating_distance_between_two_gps_points-t3708.html 获得maps api的方法:本人的 打开Eclipse--->Windows--->Preferences--->Android--->Build 查看默认的debug keystore位置,我的是C:\Documents and Settings\Administrator\Local Settings\Application Data\Android\debug.keystore 启动命令行 直接 输入如下内容: keytool -list -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator\Local Settings\Application Data\Android\debug.keystore" -storepass android -keypass android 结果如下:Microsoft Windows XP [版本 5.1.2600] (C) 版权所有 1985-2001 Microsoft Corp. C:\Documents and Settings\Administrator>keytool -list -alias androiddebugkey -ke ystore "C:\Documents and Settings\Administrator\Local Settings\Application Data\ Android\debug.keystore" -storepass android -keypass android androiddebugkey, 2009-3-12, keyEntry, 认证指纹 (MD5): 0F:C3:F0:C6:32:49:CE:C6:0E:18:57:CA:48:D7:CD:12 C:\Documents and Settings\Administrator> 屏幕图如下: 打开http://code.google.com/intl/zh-CN/android/maps-api-signup.html 填入你的认证指纹(MD5)即可获得apiKey了 0Ua9BENcUvNLXp8wn_vXXvVf70rLTYixrNxbHNQ http://www.androidcompetencycenter.com/category/android-api/ http://duzike.blogbus.com/logs/35386568.html http://www.helloandroid.com/node/206 http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351.html 根据输入城市名动态加载google地图 文章出处:http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351.html 1)SendCityName.java: package com.google.android.citygmapview; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class SendCityName extends Activity { protected static final int REQUEST_SEND_DATA = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); getAndSendCityName(); } public void getAndSendCityName() { Button btn = (Button)findViewById(R.id.confirm); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { EditText edt=(EditText)SendCityName.this.findViewById(R.id.edt); Intent intent = new Intent(); intent.setClass(SendCityName.this, ShowGmapView.class); if(edt.getText().length()!= 0) { String data = edt.getText().toString(); String name="data"; intent.putExtra(name, data); startSubActivity(intent,REQUEST_SEND_DATA); } } }); } } 说明: if(edt.getText().length()!= 0)用来处理用户输入为空的情况,为空时数据不会传递到另外一个activity中去,节省资源。 (2)ShowGmapView.java: package com.google.android.citygmapview; import java.io.IOException; import java.util.Locale; import com.google.android.location.GmmGeocoder; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Point; import android.location.Address; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.Menu.Item; public class ShowGmapView extends MapActivity { private static final int EXIT_ID = 0; private MapView myMapView; private Address[] maddrs; protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.gmap_view); Bundle extras = getIntent().getExtras(); String name="data"; if(extras != null) { String data1 = extras.getString(name); GmmGeocoder mgc = new GmmGeocoder(Locale.getDefault()); try { maddrs = mgc.query(data1, GmmGeocoder.QUERY_TYPE_LOCATION, 0, 0, 180.0, 360.0); if (null!=maddrs && maddrs.length > 0) { Log.d("CountryName: ", maddrs[0].getCountryName()); maddrs[0].getLatitude(); } else { setResult(RESULT_OK, null, extras); finish(); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } myMapView = new MapView(this); if(null!=maddrs && maddrs.length > 0) { Point p = new Point((int) (maddrs[0].getLatitude() * 1000000), (int) (maddrs[0].getLongitude() * 1000000)); /** 地图控制器 */ MapController mc = myMapView.getController(); mc.animateTo(p); /** 21是最zoom in的一级,一共是1-21级 */ mc.zoomTo(21); setContentView(myMapView); /** 切换到卫星地图 */ myMapView.toggleSatellite(); } setResult(RESULT_OK, null, extras); } } 文章出处:http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351.html public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_I) { /** zoom in */ myMapView.getController().zoomTo(myMapView.getZoomLevel() + 1); return true; } else if (keyCode == KeyEvent.KEYCODE_O) { /** zoom out */ myMapView.getController().zoomTo(myMapView.getZoomLevel() - 1); return true; } else if (keyCode == KeyEvent.KEYCODE_S) { /** 卫星地图 */ myMapView.toggleSatellite(); return true; } else if (keyCode == KeyEvent.KEYCODE_T) { /** traffic,路况 */ myMapView.toggleTraffic(); return true; } return false; } 文章出处:http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351_2.html @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, EXIT_ID, R.string.exit_gmap); return true; } @Override public boolean onMenuItemSelected(int featureId, Item item) { super.onMenuItemSelected(featureId, item); switch(item.getId()) { case EXIT_ID: finish(); break; } return true; } } 说明: 在开始设计时采用了Geocoder这个类,但似乎通过它获取的经纬度为空值,所以最后采取了GmmGeocoder,并能达到目的。 图示: (3)main.xml: (4)gmap_view.xml: (5)strings.xml: city gmap view confirm Exit google map (6)AndroidManifest.xml: 文章出处:http://www.diybl.com/course/6_system/linux/Linuxjs/2008819/136351_3.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值