安卓---高德地圖API應用

說明:定位須要導入android_location 的jar包,若是沒有會報錯,這個官方網站好像找不到,這是我在網上找到的一個連接html

http://download.csdn.net/detail/raindays1/9469464java

 導航和路線規劃寫在我另外一篇博客:http://www.cnblogs.com/rainday1/p/5550857.htmlandroid

如今的地圖接口更新太快,本人才接觸安卓沒多久,對於地圖的應用還不能隨機應變。剛開始原本想用百度地圖的API,但是一直報錯,網上也沒找到合適的解決方法,一氣之下把原來的工程刪除了,轉手高德地圖,都說高德有詳細的開發文檔,可是更新後的高德也和開發文檔有些許出入。參照着http://www.cnblogs.com/ouyangduoduo/p/4619407.html博客把最基本的地圖層顯示出來了。git

關於申請高德地圖API Key的步驟我這裏不作詳細介紹,官方網上有說明。直接應用顯示地圖,新建工程導入jar包,方法在我上一片博客中有圖文說明,這裏就直接省略api

把從官網上下載的文件解壓到本身的電腦,而後把文件包裏面的東西都拷到工程中去(2.0以後不須要單獨導入Locationjar包)網絡

1.app

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
       
        
		<meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="本身的key"/>
      <!--<service android:name="com.amap.api.location.APSService"></service>2.0以前不須要,2.0以後定位必須加上-->
        
        <activity
            android:name="com.example.bmap.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>
    </application>

 2.ide

  android 高德地圖定位服務啓動失敗,此爲定位須要的服務,使用2.0以上的定位就須要這個。2.0以後不須要單獨導入定位包
  在官方提供的demo中其實就已經寫到了,只是新手通常在添加權限以後就不太會注意到AndroidManifest中的此點。
  加上以後定位功能就能夠實現了‍
 在AndroidManifest中添加,如上面標紅的地方
  <service android:name="com.amap.api.location.APSService"></service>

   <!-- //地圖包、搜索包須要的基礎權限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <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_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

 3.佈局文件activity_main.xml中添加map控件函數

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   <!-- 引入佈局文件 -->
    <com.amap.api.maps.MapView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/location"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

4. 主函數佈局

package com.example.bmap;

import android.app.Activity;
import android.os.Bundle;


import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;

public class MainActivity extends Activity  {

    private MapView mapView;
    private AMap aMap;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.location);
        mapView.onCreate(savedInstanceState);//必需要寫
        init();
        
        //夜景模式
        //aMap.setMapType(AMap.MAP_TYPE_NIGHT);
     //顯示交通圖 //aMap.setTrafficEnabled(
true); } /** * 初始化AMap對象 */ private void init() { if (aMap == null) { aMap = mapView.getMap(); } } /** * 方法必須重寫 */ @Override protected void onResume() { super.onResume(); mapView.onResume(); } /** * 方法必須重寫 */ @Override protected void onPause() { super.onPause(); mapView.onPause(); } /** * 方法必須重寫 */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } /** * 方法必須重寫 */ @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); } }

到這裏,簡單的地圖就作出來了,運行一下吧。

 

下面咱們在地圖上添加定位和天氣信息,以及跟隨/定位/旋轉

定位須要導入android_location 的jar包,若是沒有會報錯,這個官方網站好像找不到,這是我在網上找到的一個連接

http://download.csdn.net/detail/raindays1/9469464

導入jar包的方法在我上一片博客中有圖文說明,這裏就直接省略

1.AndroidManifest.xml文件裏的設置和上面的例子裏面同樣,複製下來便可,

2.佈局文件activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   <!-- 引入佈局文件 -->
    <com.amap.api.maps.MapView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/location"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

    </com.amap.api.maps.MapView>


    <TextView
        android:id="@+id/tv_weather"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignLeft="@+id/gps_radio_group"
        android:layout_alignParentTop="true"
        android:textColor="@android:color/black"
        android:textSize="28sp" />
    
       <RadioGroup
        android:id="@+id/gps_radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|left"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:background="#00101010"<!--前兩位是表明透明度,後面表明背景顏色-->
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/gps_locate_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="定位"
       <!--這個顏色要求最低 android:minSdkVersion="14"-->
            android:textColor="@android:color/holo_red_light" />

        <RadioButton
            android:id="@+id/gps_follow_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="跟隨"
            android:textColor="@android:color/holo_red_light" />

        <RadioButton
            android:id="@+id/gps_rotate_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="旋轉"
            android:textColor="@android:color/holo_red_light" />
    </RadioGroup>

</RelativeLayout>

 

 3.主函數

package com.example.bmap;

import java.util.List;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocalDayWeatherForecast;
import com.amap.api.location.AMapLocalWeatherForecast;
import com.amap.api.location.AMapLocalWeatherListener;
import com.amap.api.location.AMapLocalWeatherLive;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;

public class MainActivity extends Activity implements LocationSource, AMapLocationListener,AMapLocalWeatherListener, OnCheckedChangeListener {

	private MapView mapView;
    private AMap aMap;
    private LocationManagerProxy mLocationManagerProxy;
    private OnLocationChangedListener mListener;
    private RadioGroup mGPSModeGroup;
    
    private static final String TAG = "LocationActivity";
    
    private TextView tvWeather;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.location);
        tvWeather = (TextView) findViewById(R.id.tv_weather);
        mapView.onCreate(savedInstanceState);//必需要寫
        init();
        
        //夜景模式
        //aMap.setMapType(AMap.MAP_TYPE_NIGHT);
        aMap.setTrafficEnabled(true);

        
    }
    
    /**
     * 初始化AMap對象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        mGPSModeGroup = (RadioGroup) findViewById(R.id.gps_radio_group);
		mGPSModeGroup.setOnCheckedChangeListener(this);
		
        initLocation();
        setUpMap();
    }
    
    @Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.gps_locate_button:
			// 設置定位的類型爲定位模式
			aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
			break;
		case R.id.gps_follow_button:
			// 設置定位的類型爲 跟隨模式
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
			break;
		case R.id.gps_rotate_button:
			// 設置定位的類型爲根據地圖面向方向旋轉
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);
			break;
		}

	}

    
    /**
     * 初始化定位
     * 初始化天氣
     */
    private void initLocation(){
        
        mLocationManagerProxy = LocationManagerProxy.getInstance(this);
        //此方法爲每隔固定時間會發起一次定位請求,爲了減小電量消耗或網絡流量消耗,
        //注意設置合適的定位時間的間隔,而且在合適時間調用removeUpdates()方法來取消定位請求
        //在定位結束後,在合適的生命週期調用destroy()方法     
        //其中若是間隔時間爲-1,則定位只定一次
        mLocationManagerProxy.requestLocationData(
                LocationProviderProxy.AMapNetwork, -1, 15, this);
        //天氣請求
        mLocationManagerProxy.requestWeatherUpdates(
                LocationManagerProxy.WEATHER_TYPE_FORECAST, this);
 
        mLocationManagerProxy.setGpsEnable(false);
    }
    
    @Override
    public void onWeatherForecaseSearched(AMapLocalWeatherForecast aMapLocalWeatherForecast) {
        // TODO Auto-generated method stub
        if(aMapLocalWeatherForecast != null && aMapLocalWeatherForecast.getAMapException().getErrorCode() == 0){
             
            List<AMapLocalDayWeatherForecast> forcasts = aMapLocalWeatherForecast
                    .getWeatherForecast();
            for (int i = 0; i < forcasts.size(); i++) {
                AMapLocalDayWeatherForecast forcast = forcasts.get(i);
                switch (i) {
                //今每天氣
                case 0:
                	//城市
                    String city = forcast.getCity();
                    String today = "今天 ( "+ forcast.getDate() + " )";
                    String todayWeather = forcast.getDayWeather() + "    "
                            + forcast.getDayTemp() + "/" + forcast.getNightTemp()
                            + "    " + forcast.getDayWindPower();
                    tvWeather.setText("城市:" + city + ", " + today + ", 天氣信息:" + todayWeather);
                    break;
                //明每天氣
                case 1:
                     
                    String tomorrow = "明天 ( "+ forcast.getDate() + " )";
                    String tomorrowWeather = forcast.getDayWeather() + "    "
                            + forcast.getDayTemp() + "/" + forcast.getNightTemp()
                            + "    " + forcast.getDayWindPower();
                    tvWeather.append("; " + tomorrow + ", 天氣信息:" + tomorrowWeather);
                    break;
                //後每天氣
                case 2:
                     
                    String aftertomorrow = "後天( "+ forcast.getDate() + " )";
                    String aftertomorrowWeather = forcast.getDayWeather() + "    "
                            + forcast.getDayTemp() + "/" + forcast.getNightTemp()
                            + "    " + forcast.getDayWindPower();
                    tvWeather.append("; " + aftertomorrow + ", 天氣信息:" + aftertomorrowWeather);
                    break;
                }
            }
        }else{
            // 獲取天氣預報失敗
            Toast.makeText(this,"獲取天氣預報失敗:"+ aMapLocalWeatherForecast.getAMapException().getErrorMessage(), Toast.LENGTH_SHORT).show();
        }
        
    }

    
    private void setUpMap(){
        aMap.setLocationSource(this);// 設置定位監聽
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 設置默認定位按鈕是否顯示
        aMap.setMyLocationEnabled(true);// 設置爲true表示顯示定位層並可觸發定位,false表示隱藏定位層並不可觸發定位,默認是false
        // 設置定位的類型爲定位模式:定位(AMap.LOCATION_TYPE_LOCATE)、跟隨(AMap.LOCATION_TYPE_MAP_FOLLOW)
        // 地圖根據面向方向旋轉(AMap.LOCATION_TYPE_MAP_ROTATE)三種模式
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        
    }
 
    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        // TODO Auto-generated method stub
        mListener = onLocationChangedListener;
        if (mLocationManagerProxy == null) {
                mLocationManagerProxy = LocationManagerProxy.getInstance(this);
                //此方法爲每隔固定時間會發起一次定位請求,爲了減小電量消耗或網絡流量消耗,
                //注意設置合適的定位時間的間隔,而且在合適時間調用removeUpdates()方法來取消定位請求
                //在定位結束後,在合適的生命週期調用destroy()方法
                //其中若是間隔時間爲-1,則定位只定一次
                mLocationManagerProxy.requestLocationData(
                        LocationProviderProxy.AMapNetwork, -1, 10, this);
        }
    }
    /**
     * 中止定位
     */
    @Override
    public void deactivate() {
        // TODO Auto-generated method stub
        mListener = null;
        if (mLocationManagerProxy != null) {
            mLocationManagerProxy.removeUpdates(this);
            mLocationManagerProxy.destroy();
        }
        mLocationManagerProxy = null;
    }

    
    /**
     * 方法必須重寫
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }
 
    /**
     * 方法必須重寫
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }
     
    /**
     * 方法必須重寫
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
 
    /**
     * 方法必須重寫
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

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

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

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

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}

	 @Override
	 public void onLocationChanged(AMapLocation aMapLocation) {
	        // TODO Auto-generated method stub
	        if(aMapLocation != null && aMapLocation.getAMapException().getErrorCode() == 0){
	            //獲取位置信息
	            Double geoLat = aMapLocation.getLatitude();
	            Double geoLng = aMapLocation.getLongitude();  
	            Log.d(TAG, "Latitude = " + geoLat.doubleValue() + ", Longitude = " + geoLng.doubleValue());
	            
	            // 經過 AMapLocation.getExtras() 方法獲取位置的描述信息,包括省、市、區以及街道信息,並以空格分隔。
	            String desc = "";
	            Bundle locBundle = aMapLocation.getExtras();
	            if (locBundle != null) {
	                    desc = locBundle.getString("desc");
	                    Log.d(TAG, "desc = " + desc);
	            }
	            mListener.onLocationChanged(aMapLocation);// 顯示系統小藍點
	        }
	    }

	@Override
	public void onWeatherLiveSearched(AMapLocalWeatherLive arg0) {
		// TODO Auto-generated method stub
		
	}

}

 運行結果以下:旋轉的時候個人模擬器會中止運行,沒讓顯示全就急忙截圖了

相關文章
相關標籤/搜索