android学习笔记(二)map

连续几天调试,终于可以让自己的map程序显示出地图了,经验积累如下:

 

地图显示需要mapview类,该类应放在mapactivity中,controller则可以控制地图的伸缩大小(从mapview中得来)。

当然首先我们必须保证申请到apikey,具体信息可参考

http://code.google.com/intl/zh-CN/android/add-ons/google-apis/maps-overview.html

先来看下布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/maplayout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
<com.google.android.maps.MapView
	android:id="@+id/viewMap"
	android:enabled="true"
	android:clickable="true"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:apiKey="0shqezR5L4dW47pyzE4RxOTIOV1lqoP6uInPQGw"/>
	
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
	android:layout_height="wrap_content" 
	android:layout_width="wrap_content" 
	android:text="@string/lat" 
	android:id="@+id/textView1">
</TextView>
<EditText 
	android:text="EditText" 
	android:layout_height="wrap_content" 
	android:layout_width="wrap_content" 
	android:id="@+id/latitude">
</EditText>
<TextView 
	android:layout_height="wrap_content" 
	android:layout_width="wrap_content" 
	android:text="@string/lon" 
	android:id="@+id/textView2">
</TextView>
<EditText 
	android:text="EditText" 
	android:layout_height="wrap_content" 
	android:layout_width="wrap_content" 
	android:id="@+id/longitude">
</EditText>
<Button 
	android:id="@+id/showmap" 
	android:text="Button" 
	android:layout_height="wrap_content" 
	android:layout_width="wrap_content">
</Button>

</LinearLayout>

</RelativeLayout>

将apikey放入代码中,注意在main.xml这个布局文件中,mapview标签需用全称,如

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

然后manifest.xml文件中<application>标签下添加<uses-library android:name="com.google.android.maps" />,注意要添加

 

到<application>下(我开始一时大意,添加到了<activity>下)

 

接下来需要设置程序访问权限,


<manifest>标签下添加


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


那么完整的manifest.xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0">
      
	<uses-permission android:name="android.permission.INTERNET" />
	
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MapTest"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
		<uses-library android:name="com.google.android.maps" />
    </application>
</manifest>

再贴上java文件:

package com.test;

import com.google.android.maps.*;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class MapTest extends MapActivity {
	
	private MapView viewMap;
	private Button showbutton;
	private EditText address_lat;
	private EditText address_lon;
	private MapController controller;
	
	private double lat = 25.040225;
	private double lon = 121.52374;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        viewMap = (MapView)findViewById(R.id.viewMap);
        showbutton = (Button)findViewById(R.id.showmap);
        address_lat = (EditText)findViewById(R.id.latitude);
        address_lon = (EditText)findViewById(R.id.longitude);
        controller = viewMap.getController();
        viewMap.setSatellite(false);
        viewMap.setStreetView(true);
        controller.setZoom(17);
           
        refreshMap();
        
        showbutton.setOnClickListener(new OnClickListener(){
        	

			@Override
			public void onClick(View v) {
				
				// TODO Auto-generated method stub
				boolean input_is_ok = inputCheck();
				if(input_is_ok)
				{
					lat = Double.parseDouble(address_lat.getText().toString());
					lon = Double.parseDouble(address_lon.getText().toString());
					refreshMap();
				}
				else
				{
					//showDialog(1);
				}
			}
        	
        });
    }
    
    private boolean inputCheck()
    {
    	if(address_lat.getText().toString().equals("") || address_lon.getText().toString().equals(""))
    		return false;
    	else
    		return true;
    }

    private void refreshMap() {
    	GeoPoint point = new GeoPoint((int)(lat * 1e6), (int)(lon * 1e6));
    	viewMap.displayZoomControls(true);
    	controller.animateTo(point);
    	controller.setZoom(17);
    }

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

如果你想要实现一个简单的地图缩放功能,可以使用mapview中的setBuiltInZoomControls(boolean on)

如:

viewmap.setBuiltInZoomControls(true);

这样我们可以得到一个控制缩放的控件。

涉及到GPS定位的问题,还需要用到其他类。

Location,该对象包含地理位置信息。在跟踪位置的过程中,我们需要实时的得到Location对象。

通过LocationManager对象中的

public Location getLastKnownLocation (String provider)方法我们可以得到当前的location对象。

参数provider是locationprovider的名字。

LocationProvider根据我现在的理解,该对象指的应该是定位模式,我们知道定位模式一般有gps定位,基站定位,

network定位,WIFI定位等,android提供给我们两种provider,分别是:LocationManager.NETWORK_PROVIDER和LocationManager.GPS_PROVIDER

前者用于移动网络中获取位置,精度较低但速度很快,后者使用GPS进行定位,精度很高但一般需要10-60秒时间才能开始第1次定位,如果是在室内则基本上无法定位。

当然,我们也可以重写自己的provider。

举一个简单的栗子:

package com.test;

import java.util.List;

import com.google.android.maps.*;

import android.app.Activity;
import android.content.Context;
import android.location.*;
import android.os.Bundle;
import android.util.Log;
import android.widget.*;

public class MapUpdate extends MapActivity {
	
	private MapView viewmap;
	private LocationManager managerlocation;
	private Location currentLocation;
	private Criteria ct;
	private MapController mcontrol;
	private String locpro;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        viewmap = (MapView) findViewById(R.id.viewMap);
        mcontrol = viewmap.getController();
        managerlocation = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        
        viewmap.setBuiltInZoomControls(true);
  
        
        //通过criteria对象,设置位置数据的标准,以便系统根据需要为我们选取合适的provider
        ct = new Criteria();
        ct.setAccuracy(Criteria.ACCURACY_FINE);
        ct.setAltitudeRequired(false);
        ct.setBearingRequired(false);
        ct.setCostAllowed(true);
        ct.setPowerRequirement(Criteria.POWER_LOW);
        
        currentLocation = getCurrentLocation(managerlocation, ct);
        
        if (currentLocation == null)
        {
        	Log.d("test", "currentLocation is null");
        }
        else
        {
        	refreshMylocation(currentLocation);
        }
        
        LocationListener lolis = new LocationListener(){

			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				refreshMylocation(location);
			}

			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				// TODO Auto-generated method stub
				
			}
        	
        };
        
        managerlocation.requestLocationUpdates(locpro, 5000, 10, lolis);
    }
    
    private void refreshMylocation(Location cl) {
		// TODO Auto-generated method stub
		double lat = cl.getLatitude() * 1e6;
		double lon = cl.getLongitude() * 1e6;
		GeoPoint gp = new GeoPoint((int)lat, (int)lon);
		
		RouteOverlay routepoint = new RouteOverlay(gp);
		viewmap.getOverlays().add(routepoint);
		
		mcontrol.animateTo(gp);
	}

	private Location getCurrentLocation(LocationManager lm, Criteria ct){
		
    	Location cl = null;
    	
    	locpro = lm.getBestProvider(ct, true);
    	
    	//Log.d("providername", locpro);
    	
    	try
    	{
    		cl = lm.getLastKnownLocation(locpro);
    	}catch(Exception e){
    		Log.d("LocationException", e.toString() + " ");
    		e.printStackTrace();
    	}
    	
    	if (locpro == null)
    	{
    		Log.d("providertest", "locationprovider is null");
    	}
    	else
    	{
    		Log.d("providertest", "locationprovider is ok");
    	}
    	
    	if(cl == null)
    	{
    		Log.d("LocationTest", "location is null");
    	}
    	
    	return cl;
    	
    }

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






你可能感兴趣的:(android学习笔记(二)map)