Android实战--基于位置的服务(获取自己位置的经纬度+百度地图)

需要借助LocationManager类实现,下面直接看代码:

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

    <TextView
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


.java代码如下:

package org.lxh.demo;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class Hello extends Activity {
	private TextView textView;
	private LocationManager locationManager;
	private String provider;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); // 生命周期方法

		super.setContentView(R.layout.main); // 设置要使用的布局管理器
		Log.d("111111", "4444444");
		textView = (TextView) findViewById(R.id.edit);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		List<String> providerList = locationManager.getProviders(true);// 获取所有可用的位置提供器
		if (providerList.contains(LocationManager.GPS_PROVIDER)) {
			provider = LocationManager.GPS_PROVIDER;
		} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
			provider = LocationManager.NETWORK_PROVIDER;
			Log.d("111111", "3333333");

		} else {
			Toast.makeText(this, "No location provider to use!",
					Toast.LENGTH_SHORT).show();
			return;
		}
		Location location = locationManager.getLastKnownLocation(provider);
		if (location != null) {
			showLocation(location);
		}
		locationManager.requestLocationUpdates(provider, 5000, 1,
				locationListener);

	}

	private void showLocation(Location location) {
		String crrrentPositionString = "latitude is" + location.getLatitude()
				+ "\n" + "longitude is" + location.getLongitude();
		textView.setText(crrrentPositionString);

	}

	LocationListener locationListener = new LocationListener() {

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

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

		}

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

		}

		public void onLocationChanged(Location location) {
			showLocation(location);// 更新当前设备信息
			Log.d("111111", "222222");

		}
	};

	protected void onDestroy() {
		super .onDestroy();
		if (locationManager != null) {
			locationManager.removeUpdates(locationListener);
		}
	};
}


AndroidManifest.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest 
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="org.lxh.demo" 
	android:versionCode="1" 
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="10" />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/><!-- 声明权限 -->
	<application 
		android:icon="@drawable/icon" 
		android:label="@string/app_name">
		<activity 
			android:name=".Hello" 
			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>
	
</manifest>


运行实例就可以显示你的当前经纬度,下面我们主要介绍一下怎么使用百度地图:

首先你要申请一个API Key,具体方法可以百度一下,都搞完了以后把jar包下载下来:

技术分享

导入开发包:

技术分享

然后设置布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.baidu.mapapi.map.MapView
        android:id="@+id/map_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true" />

</LinearLayout>


然后修改MainActivity.java文件:

package com.example.baidumaptest;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;

public class MainActivity extends Activity {

	private BMapManager manager;

	private MapView mapView;

	private LocationManager locationManager;

	private String provider;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		manager = new BMapManager(this);
		// API Key需要替换成你自己的
		manager.init("SHVPoTtIpzfonPD3HCkc5sIt", null);
		setContentView(R.layout.activity_main);
		mapView = (MapView) findViewById(R.id.map_view);
		mapView.setBuiltInZoomControls(true);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// 获取所有可用的位置提供器
		List<String> providerList = locationManager.getProviders(true);
		if (providerList.contains(LocationManager.GPS_PROVIDER)) {
			provider = LocationManager.GPS_PROVIDER;
		} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
			provider = LocationManager.NETWORK_PROVIDER;
		} else {
			// 当没有可用的位置提供器时,弹出Toast提示用户
			Toast.makeText(this, "No location provider to use",
					Toast.LENGTH_SHORT).show();
			return;
		}
		Location location = locationManager.getLastKnownLocation(provider);
		if (location != null) {
			navigateTo(location);
		}
	}

	private void navigateTo(Location location) {
		MapController controller = mapView.getController();
		// 设置缩放级别
		controller.setZoom(16);
		GeoPoint point = new GeoPoint((int) (location.getLatitude() * 1E6),
				(int) (location.getLongitude() * 1E6));
		// 设置地图中心点
		controller.setCenter(point);
		MyLocationOverlay myLocationOverlay = new MyLocationOverlay(mapView);
		LocationData locationData = new LocationData();
		// 指定我的位置
		locationData.latitude = location.getLatitude();
		locationData.longitude = location.getLongitude();
		myLocationOverlay.setData(locationData);
		mapView.getOverlays().add(myLocationOverlay);
		// 刷新使新增覆盖物生效
		mapView.refresh();
		PopupOverlay pop = new PopupOverlay(mapView, new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {
				// 相应图片的点击事件
				Toast.makeText(MainActivity.this,
						"You clicked button " + index, Toast.LENGTH_SHORT)
						.show();
			}
		});
		// 创建一个长度为3的Bitmap数组
		Bitmap[] bitmaps = new Bitmap[3];
		try {
			// 将三张图片读取到内存中
			bitmaps[0] = BitmapFactory.decodeResource(getResources(),
					R.drawable.left);
			bitmaps[1] = BitmapFactory.decodeResource(getResources(),
					R.drawable.middle);
			bitmaps[2] = BitmapFactory.decodeResource(getResources(),
					R.drawable.right);
		} catch (Exception e) {
			e.printStackTrace();
		}
		pop.showPopup(bitmaps, point, 18);
	}

	@Override
	protected void onDestroy() {
		mapView.destroy();
		if (manager != null) {
			manager.destroy();
			manager = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		mapView.onPause();
		if (manager != null) {
			manager.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		mapView.onResume();
		if (manager != null) {
			manager.start();
		}
		super.onResume();
	}

}


配置AndroidManifest.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.baidumaptest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.baidumaptest.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>

</manifest>

运行实例:


技术分享

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。