Android使用GPS定位及在googlemap添加標記

要使用googlemap,Activity要繼承MapActivity.  MapActivity是使用的google第三方API,所以要在配置文件中聲明.  廢話不多說,上代碼:

manifest.xml中:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package
="com.t2cn.map"
android:versionCode
="1"
android:versionName
="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MapViewActivity"
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_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>

注意一定要加<uses-library android:name="com.google.android.maps" />,並且加在<application></application>中,否則運行時會有classNotFoundException.

Activity:

public class MapViewActivity extends com.google.android.maps.MapActivity{
private LocationListener locationListener;
TextView tv1;
GeoPoint gp;
MapView mapView;
private Criteria criteria;
View popView;
private Handler mHandler;
private Location location;
private MapController mapController;
private LocationManager locationManager;
int i;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.tv);
tv1
= (TextView) this.findViewById(R.id.tv1);
openGPSSettings();
//判斷是否開啓GPS
mHandler = new MyHandler();
mHandler.post(runnable);
getLocation();
setMapView();

}
/**
* 判斷是否開啓GPS
*/
private void openGPSSettings() {
LocationManager alm
= (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(
this, "GPS模塊正常", Toast.LENGTH_SHORT).show();
return;
}

Toast.makeText(
this, "請開啓GPS!", Toast.LENGTH_SHORT).show();
Intent intent
= new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivityForResult(intent,
0); //此爲設置完成後返回到獲取界面

}
/**
* 設置地圖顯示
*/
private void setMapView(){
this.mapView = (MapView) this.findViewById(R.id.map);
this.mapView.setBuiltInZoomControls(true);//可以多點觸摸放大
mapView.setStreetView(true);
mapView.setBuiltInZoomControls(
true);
this.mapController = mapView.getController();
mapController.setZoom(
14);

Drawable drawable
= this.getResources().getDrawable(R.drawable.marker);
//設置圖片的繪製區域大小
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
this.mapController.animateTo(gp);//通過動畫方式移動到指定座標
setView();//設置彈出框
MyOverlay myOverlay = new MyOverlay(drawable,this);
myOverlay.addOverlay(
new OverlayItem(gp, "hello", "i'm in Athens,Greece!"));
mapView.getOverlays().add(myOverlay);
}
/**
* 設置地圖標記彈出框樣式
*/
private void setView(){
//popView不爲null,即界面刷新重新調用setMapView的時候不用重新創建popView,否則原來popView的監聽事件不啓作用
if(popView==null){
popView
= super.getLayoutInflater().inflate(R.layout.pop, null);
mapView.addView(popView,
new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT, MapView.LayoutParams.WRAP_CONTENT,
null, MapView.LayoutParams.BOTTOM_CENTER));
popView.setVisibility(View.GONE);
}
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
/**
* 獲取位置信息
*/
private void getLocation(){
// 獲取位置管理服務
String serviceName = Context.LOCATION_SERVICE;
locationManager
= (LocationManager) this.getSystemService(serviceName);
// 查找到服務信息
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// 高精度
criteria.setAltitudeRequired(false); //不要求海拔信息
criteria.setBearingRequired(false); //不要求方位信息
criteria.setCostAllowed(true); //是否允許付費
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
String provider = locationManager.getBestProvider(criteria, true); // 獲取GPS信息
location = locationManager.getLastKnownLocation(provider); // 通過GPS獲取位置
updateToNewLocation(location);
// 設置監聽器,自動更新的最小時間爲間隔N秒(1秒爲1*1000,這樣寫主要爲了方便)或最小位移變化超過N米
locationListener = new LocationListener(){

@Override
public void onLocationChanged(Location location) {
updateToNewLocation(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

}

};
locationManager.requestLocationUpdates(provider,
100 * 1000, 500,locationListener);
}
/**
* 獲取GeoPoint
*/
private void updateToNewLocation(Location location) {
if(true){
double latitude = 31.16520805*1E6;
double longitude = 121.4000644*1E6;
// if (location != null) {
// double latitude = location.getLatitude()*1E6;
// double longitude = location.getLongitude()*1E6;
gp = new GeoPoint((int) latitude, (int) longitude);
tv1.setText(
"維度:" + latitude+ "\n經度" + longitude);
}
else {
tv1.setText(
"無法獲取地理信息");
}
}
/**
* 發送位置信息到服務器
*/
Runnable runnable
= new Runnable(){
@Override
public void run() {
String provider
= locationManager.getBestProvider(criteria, true);
location
= locationManager.getLastKnownLocation(provider);
// double lat = location.getLatitude()*1E6;
// double lon = location.getLongitude()*1E6;
double lat = 31.16520805*1E6;
double lon = 121.4000644*1E6;
mHandler.postDelayed(runnable,
10*1000);
Message message
= mHandler.obtainMessage();
message.arg1
= (int)lat;
message.arg2
= (int)lon;
mHandler.sendMessage(message);
}
};
/**定義MyHandler*/
/**
* 自定義Handler
*/
class MyHandler extends Handler{
public void handleMessage(Message msg) {
i
++;
super.handleMessage(msg);
int lat = msg.arg1;
int lon = msg.arg2;
gp
= new GeoPoint((int) lat, (int) lon);
mapController.setCenter(gp);
setMapView();
mapView.invalidate();
tv1.setText(i
+": "+"維度:" + lat+ "\n經度" + lon);
//tv1.invalidate();
};
}
}

地圖覆蓋物MyOverlay類:

public class MyOverlay extends ItemizedOverlay{
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private MapViewActivity context;
private TextView textView1,textView2;
public MyOverlay(Drawable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public MyOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = (MapViewActivity)context;
}
@Override
protected OverlayItem createItem(int arg0) {
// TODO Auto-generated method stub
return mapOverlays.get(arg0);
}

@Override
public int size() {
// TODO Auto-generated method stub
return mapOverlays.size();
}

protected boolean onTap(int index) {
MapView.LayoutParams geoLP
= (MapView.LayoutParams)context.popView.getLayoutParams();
geoLP.point
= mapOverlays.get(index).getPoint();
context.mapView.updateViewLayout(context.popView, geoLP);
context.popView.setVisibility(View.VISIBLE);
textView1
= (TextView) context.popView.findViewById(R.id.map_bubbleTitle);
textView2
= (TextView) context.popView.findViewById(R.id.map_bubbleText);
textView1.setText(mapOverlays.get(index).getTitle());
textView2.setText(mapOverlays.get(index).getSnippet());
context.popView.setVisibility(View.VISIBLE);
ImageView imageView
= (ImageView) context.popView.findViewById(R.id.map_bubbleImage);
imageView.setOnClickListener(
new View.OnClickListener(){
@Override
public void onClick(View v) {
context.popView.setVisibility(View.GONE);
}
});
return true;
}

public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
populate();
}
}

用到的圖片:

        

layout文件:

tv.xml 用來顯示地圖

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/tv1"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
/>
<com.google.android.maps.MapView
android:id="@+id/map"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:enabled
="true"
android:clickable
="true"
android:apiKey
="04lsJg9XJO11W63yc6Q3vsfb0HTJgiYxtTlCiGg"
/>
</LinearLayout>

pop.xml 用來顯示地圖覆蓋物的彈出框

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background
="@drawable/bubble_background"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:paddingLeft
="5px"
android:paddingTop
="5px"
android:paddingRight
="5px"
android:paddingBottom
="20px"
>

<TextView android:id="@+id/map_bubbleTitle"
android:ellipsize
="marquee"
android:layout_width
="120px"
android:layout_height
="wrap_content"
android:gravity
="center_horizontal"
android:singleLine
="true" />
<ImageView android:id="@+id/map_bubbleImage"
android:background
="@drawable/close"
android:layout_width
="30px"
android:layout_toRightOf
="@id/map_bubbleTitle"
android:layout_height
="wrap_content" />

<TextView android:id="@+id/map_bubbleText"
android:layout_width
="150px"
android:layout_below
="@id/map_bubbleTitle"
android:layout_height
="wrap_content"
android:singleLine
="false" />


</RelativeLayout>

OK。 搞定


文章來自:http://www.cnblogs.com/yyyyy5101/archive/2011/05/27/2060172.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章