<?xml version="1.0"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.itcast.main"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"android:label="@string/app_name">
<activity android:name=".Main"
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>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FIND_LOCATION"/>
</manifest>
Main.java文件
package cn.itcast.main;
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 android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.TextView;
public class Main extends MapActivity{
private MapController mapController;
private GeoPoint geoPoint;
private String msg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//獲得mapview
MapView mapView=(MapView) this.findViewById(R.id.mapview);
//地圖的顯示格式爲交通圖
mapView.setTraffic(true);
//設置可控
mapView.setClickable(true);
mapView.setEnabled(true);
mapView.setBuiltInZoomControls(true);
//得到gps設備的訪問
LocationManager locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//設置gps定位配置
Criteria criteria=new Criteria();
//設置顯示精度
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
//是否獲得海拔數據
criteria.setAltitudeRequired(false);
//是否獲得方向數據
criteria.setBearingRequired(false);
//是否允許運營商計費
criteria.setCostAllowed(true);
//設置耗電程度
criteria.setPowerRequirement(Criteria.POWER_LOW);
//獲得服務供應商
Stringprovider=locationManager.getBestProvider(criteria, true);
//獲取上一個定位點
Locationlocation=locationManager.getLastKnownLocation(provider);
//獲得gps定位座標信息
Double latitude=location.getLatitude()*1E6;
Double longitude=location.getLongitude()*1E6;
//獲得衛星定位點
geoPoint=new GeoPoint(latitude.intValue(),longitude.intValue());
//獲得地圖控制器
mapController=mapView.getController();
//設置地圖顯示初始化精度
mapController.setZoom(12);
mapController.animateTo(geoPoint);
//實例化自定義繪圖層
MyOverlay myOverlay=new MyOverlay();
//爲mapview添加繪圖層
mapView.getOverlays().add(myOverlay);
//定義一個final,TextView,以備子類引用
final TextView textView=(TextView) findViewById(R.id.textview);
LocationListener locationListener=new LocationListener(){
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generatedmethod stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generatedmethod stub
}
@Override
public void onLocationChanged(Location location) {
Double latitude=location.getLatitude()*1E6;
Double longitude=location.getLongitude()*1E6;
try {
//獲得精度緯度字符串
msg = "經度:" + location.getLongitude() + "\n";
msg += "緯度:" + location.getLatitude() + "\n";
//根據經緯度獲得改點地址信息
Geocoder gc=new Geocoder(Main.this);
List<Address> addresses=gc.getFromLocation(latitude, longitude,1);
if (addresses.size()>0) {
//獲得地址信息
msg+="AddressLine:"+addresses.get(0).getAddressLine(0)+"\n";
//獲得國家名
msg += "CountryName:" + addresses.get(0).getCountryName()+"\n";
msg += "Locality:" + addresses.get(0).getLocality() + "\n";
msg += "FeatureName:" + addresses.get(0).getFeatureName();
}
textView.setText(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
};
//註冊位置監聽器,1秒鐘掃描1次
locationManager.requestLocationUpdates(provider, 1000, 0, locationListener);
}
class MyOverlay extends Overlay{
//保證觸控事件不重複操作
private int count=0;
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
//定義畫筆
Paint paint=new Paint();
paint.setColor(Color.RED);
//定義屏幕點
Point screenPoint=new Point();
//gps點轉屏幕點
mapView.getProjection().toPixels(geoPoint, screenPoint);
//獲得gps標誌點圖片
Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.flag);
//繪製gps點圖片
canvas.drawBitmap(bitmap,screenPoint.x,screenPoint.y, paint);
//繪製文字說明
canvas.drawText("當前位置", screenPoint.x, screenPoint.y, paint);
return super.draw(canvas, mapView, shadow, when);
}
@Override
public boolean onTouchEvent(MotionEvent e, MapView mapView) {
//定義一個屏幕點
Point screenPoint=new Point();
//把gps點變成屏幕點
mapView.getProjection().toPixels(geoPoint, screenPoint);
//獲得觸點座標
int currentX=(int) e.getX();
int currentY=(int) e.getY();
//在50,30範圍內觸碰,顯示當前經緯度
if ((currentX-screenPoint.x)>=0&&(currentX-screenPoint.x)<50
&&(currentY-screenPoint.y>=0)&&(currentY-screenPoint.y)<30) {
if (count==0) {
new AlertDialog.Builder(Main.this).setMessage(msg)
.setPositiveButton("確定",new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
count=0;
}
}).show();
}
count++;
}
return super.onTouchEvent(e, mapView);
}
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generatedmethod stub
return false;
}
}
注1:如果你的手機上沒有gps定位系統,會有以下錯誤
08-10 13:04:55.610:ERROR/AndroidRuntime(492): java.lang.RuntimeException: Unable to start activityComponentInfo{cn.itcast.main/cn.itcast.main.Main}: java.lang.IllegalArgumentException:provider==null
注2:記得去google官網
http://code.google.com/intl/zh-CN/android/maps-api-signup.html
申請自己機器的apikey
C:\Documents and Settings\Administrator\.android>keytool -list-keystore debug.kEystore
默認密碼android
我機器的apikey,你用不好使
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0EITsWoXq7NC_mgKW6yIxIViNLhMGsIW4dbmlsg
/>
最終實現效果:隨着android客戶端得移動,在地圖上提供精確的當前所在位置
以上是本文關於Android 客戶端GPS定位的源碼,希望本文對廣大安卓開發者有所幫助,感謝閱讀本文。更多安卓技術問題歡迎加羣探討:278744577,驗證碼:csl,不寫驗證不予通過喲~