每一台电脑都要申请属于自己的android:apiKey,要是使用别人的android:apiKey,
则地图只显示方格,不会有实际的地图出现,并且在Android虚拟机重建或者重装电脑的操作系统的时候
也要重新申请android:apiKey,关于如何申请,我在“申请Google Map服务”中已说得很详细。
新建一个地图项目。
在main.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">
<com.google.android.maps.MapView
android:id="@+id/mapview"
android:clickable="true" android:enabled="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0Pm9QrsSh_mwtc6rMyqZMRu71qFpIB51UXVWHmg" />
</LinearLayout>
在MyOverlayImpl.java中:
package com.li.googlemapproject;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class MyOverlayImpl extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> allOverlayItems = new ArrayList<OverlayItem>();
private Context context = null;
public MyOverlayImpl(Drawable defaultMarker, Context context) {
super(boundCenter(defaultMarker));
this.context = context;
}
@Override
protected OverlayItem createItem(int i) {
return this.allOverlayItems.get(i);
}
@Override
public int size() {
return this.allOverlayItems.size();
}
@Override
protected boolean onTap(int index) { // 单击标记图片之后的操作
OverlayItem item = this.allOverlayItems.get(index); // 取得指定的点
Dialog dialog = new AlertDialog.Builder(this.context)
.setIcon(R.drawable.pic_m).setTitle(item.getTitle())
.setMessage(item.getSnippet())
.setPositiveButton("关闭", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).create();
dialog.show();
return true;
}
public void addOverlayItem(OverlayItem item) {
this.allOverlayItems.add(item);
super.populate();
}
}
在PaintLineOverlay.java中:
package com.li.googlemapproject;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
public class PaintLineOverlay extends Overlay {
private GeoPoint beginGeoPoint = null;
private GeoPoint endGeoPoint = null;
public PaintLineOverlay(GeoPoint beginGeoPoint, GeoPoint endGeoPoint) {
this.beginGeoPoint = beginGeoPoint;
this.endGeoPoint = endGeoPoint;
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Paint paint = new Paint();
paint.setStyle(Style.FILL_AND_STROKE);
paint.setStrokeWidth(3);
paint.setColor(Color.RED);
Point beginPoint = new Point();
Point endPoint = new Point();
Projection projection = mapView.getProjection();
projection.toPixels(this.beginGeoPoint, beginPoint);
projection.toPixels(this.endGeoPoint, endPoint);
canvas.drawLine(beginPoint.x, beginPoint.y, endPoint.x, endPoint.y,
paint);
}
}
在PaintPointOverlay.java中:
package com.li.googlemapproject;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
public class PaintPointOverlay extends Overlay {
private GeoPoint geoPoint = null;
public PaintPointOverlay(GeoPoint geoPoint) {
this.geoPoint = geoPoint;
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Point point = new Point();
Projection projection = mapView.getProjection();
projection.toPixels(this.geoPoint, point); // 将地图上坐标的点设置为绘图屏幕的点
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(point.x, point.y, 6, paint);
}
}
在MyGoogleMapDemo.java中:
package com.li.googlemapproject;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
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.MyLocationOverlay;
public class MyGoogleMapDemo extends MapActivity {
private MapView mapView = null;
private int longitudeE6 = 0;
private int latitudeE6 = 0;
private LocationManager locationManager = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.mapView = (MapView) super.findViewById(R.id.mapview); // 取得地图视图
this.mapView.setBuiltInZoomControls(true);
// 给定一个坐标:北海银滩的坐标:109.15,21.40
this.longitudeE6 = (int) (109.15 * 1E6);
this.latitudeE6 = (int) (21.40 * 1E6);
GeoPoint point = new GeoPoint(this.latitudeE6, this.longitudeE6); // 要标记的坐标
MyLocationOverlay myloc = new MyLocationOverlay(this, this.mapView);
myloc.enableMyLocation(); // 注册GPS更新我的位置
myloc.enableCompass(); // 开启磁场感应
this.mapView.getOverlays().add(myloc);
MapController mapController = this.mapView.getController();
mapController.animateTo(point); // 设置坐标的动画
mapController.setCenter(point);
mapController.setZoom(16); // 最大的级别是16
this.locationManager = (LocationManager) super
.getSystemService(Context.LOCATION_SERVICE);
this.locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, new LocationListenerImpl());
}
private class LocationListenerImpl implements LocationListener {
public void onLocationChanged(Location location) {
MyGoogleMapDemo.this.longitudeE6 = (int) (location.getLongitude() * 1E6);
MyGoogleMapDemo.this.latitudeE6 = (int) (location.getLatitude() * 1E6);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
在AndroidManifest.xml中修改权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.li.googlemapproject"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyGoogleMapDemo"
android:label="@string/title_activity_my_google_map_demo" >
<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"/>
</manifest>
每一台电脑都要申请属于自己的android:apiKey,要是使用别人的android:apiKey,
则地图只显示方格,不会有实际的地图出现,并且在Android虚拟机重建或者重装电脑的操作系统的时候
也要重新申请android:apiKey,关于如何申请,我在“申请Google Map服务”中已说得很详细。
新建一个地图项目。
准备两个图片,名字分别为:pic_m、arrow
在main.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">
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableRow>
<EditText
android:id="@+id/msg"
android:layout_width="200px"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="检索周边信息" />
</TableRow>
</TableLayout>
<com.google.android.maps.MapView
android:id="@+id/mapview"
android:clickable="true" android:enabled="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0Pm9QrsSh_mwtc6rMyqZMRu71qFpIB51UXVWHmg" />
</LinearLayout>
在MyOverlayImpl.java中:
package com.li.geocode;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class MyOverlayImpl extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> allOverlayItems = new ArrayList<OverlayItem>();
private Context context = null;
public MyOverlayImpl(Drawable defaultMarker, Context context) {
super(boundCenter(defaultMarker));
this.context = context;
}
protected OverlayItem createItem(int i) {
return this.allOverlayItems.get(i);
}
public int size() {
return this.allOverlayItems.size();
}
protected boolean onTap(int index) { // 单击标记图片之后的操作
OverlayItem item = this.allOverlayItems.get(index); // 取得指定的点
Dialog dialog = new AlertDialog.Builder(this.context)
.setIcon(R.drawable.pic_m).setTitle(item.getTitle())
.setMessage(item.getSnippet())
.setPositiveButton("关闭", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).create();
dialog.show();
return true;
}
public void addOverlayItem(OverlayItem item) {
this.allOverlayItems.add(item);
super.populate();
}
}
在MyGeocodeDemo.java中:
package com.li.geocode;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MyGeocodeDemo extends MapActivity {
private EditText msg = null;
private Button search = null;
private MapView mapView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.search = (Button) super.findViewById(R.id.search);
this.msg = (EditText) super.findViewById(R.id.msg);
this.mapView = (MapView) super.findViewById(R.id.mapview);
this.search.setOnClickListener(new SearchOnClickListenerImpl());
}
private class SearchOnClickListenerImpl implements OnClickListener {
public void onClick(View v) {
String msg = MyGeocodeDemo.this.msg.getText().toString() ;
new SearchAsyncTask(msg).execute(0);
}
}
// 此时要根据异步处理的工具类来向Google上进行数据的提交操作,而后通过返回的JSON数据解析出具体的数据内容
private class SearchAsyncTask extends AsyncTask<Integer, String, Integer> {
private String location;
public SearchAsyncTask(String location) {
this.location = location;
}
@Override
protected void onProgressUpdate(String... values) {
GeoPoint point = new GeoPoint(
(int) (Double.parseDouble(values[0]) * 1E6),
(int) (Double.parseDouble(values[1]) * 1E6));
OverlayItem overlayItem = new OverlayItem(point, "您的位置!", values[2]);
Drawable drawable = MyGeocodeDemo.this.getResources().getDrawable(
R.drawable.arrow);
MyOverlayImpl mol = new MyOverlayImpl(drawable, MyGeocodeDemo.this);
mol.addOverlayItem(overlayItem) ;
MyGeocodeDemo.this.mapView.getOverlays().add(mol) ;
MyGeocodeDemo.this.mapView.setBuiltInZoomControls(true) ;
MyGeocodeDemo.this.mapView.getController().animateTo(point) ;
}
@Override
protected Integer doInBackground(Integer... arg0) {
Map<String, String> map = null;
try {
map = this.parseJson(this.location);
} catch (Exception e) {
e.printStackTrace();
}
if ("OK".equals(map.get("status"))) { // 操作正常
this.publishProgress(map.get("latitude"), map.get("longitude"),
map.get("address")); // 将address数据返回
} else {
this.publishProgress("没有查询结果!");
}
return null;
}
private Map<String, String> parseJson(String location) throws Exception {
Map<String, String> allMap = new HashMap<String, String>();
StringBuffer buf = new StringBuffer();
InputStream input = null;
try {
URL url = new URL(
"http://maps.google.com/maps/api/geocode/json?address="
+ URLEncoder.encode(location, "UTF-8")
+ "&sensor=false");
input = url.openStream();
Scanner scan = new Scanner(input);
while (scan.hasNext()) {
buf.append(scan.next()); // 所有的数据都保存在字符串里面
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
input.close();
}
JSONObject allData = new JSONObject(buf.toString());
allMap.put("status", allData.getString("status"));
JSONArray jsonArr = allData.getJSONArray("results");
JSONObject jsonObj = jsonArr.getJSONObject(0);
allMap.put("address", jsonObj.getString("formatted_address"));
JSONObject locationJsonObj = jsonObj.getJSONObject("geometry")
.getJSONObject("location");
allMap.put("latitude", locationJsonObj.getString("lat")) ;
allMap.put("longitude", locationJsonObj.getString("lng")) ;
return allMap;
}
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
在AndroidManifest.xml中修改权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.li.geocode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyGeocodeDemo"
android:label="@string/title_activity_my_geocode_demo" >
<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>
最近对LBS比较感兴趣,在研究百度地图。先了解下百度地图的大概吧!
http://dev.baidu.com/wiki/imap/index.php?title=Android%E5%B9%B3%E5%8F%B0/%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97
以上是百度地图在android平台上的开发指南。
基于百度地图的应用开发和google地图一样,需要一个Key,所以我们要申请一下,相对于google地图的Key来说,百度地图的Key的申请是很简单的。
申请Key的网址: http://dev.baidu.com/wiki/static/imap/key/ 当然要求是你必须得注册百度。
在百度地图的应用开发中,在Manifest要添加如下权限:
main.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"
>
<com.baidu.mapapi.MapView android:id="@+id/bmapsView"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:clickable="true" />
</LinearLayout>
MainActivity.java
1 package com.baidumap;
2
3 import com.baidu.mapapi.BMapManager;
4 import com.baidu.mapapi.GeoPoint;
5 import com.baidu.mapapi.MapActivity;
6 import com.baidu.mapapi.MapController;
7 import com.baidu.mapapi.MapView;
8
9 import android.app.Activity;
10 import android.os.Bundle;
11
12 public class MainActivity extends MapActivity {
13 private BMapManager mBMapMan;
14 @Override
15 public void onCreate(Bundle savedInstanceState) {
16 super.onCreate(savedInstanceState);
17 setContentView(R.layout.main);
18 mBMapMan = new BMapManager(getApplication());
19 mBMapMan.init("205114502786B06C4C95CEB0F55822F25E46AED2", null);
20 super.initMapActivity(mBMapMan);
21
22 MapView mMapView = (MapView) findViewById(R.id.bmapsView);
23 mMapView.setBuiltInZoomControls(true); //设置启用内置的缩放控件
24
25 mMapView.setTraffic(true);
26
27 MapController mMapController = mMapView.getController(); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放
28 GeoPoint point = new GeoPoint((int) (23.141238 * 1E6),
29 (int) (113.342331 * 1E6)); //用给定的经纬度构造一个GeoPoint,单位是微度 (度 * 1E6)
30 mMapController.setCenter(point); //设置地图中心点
31 mMapController.setZoom(12); //设置地图zoom级别
32 }
33
34 @Override
35 protected void onDestroy() {
36 if (mBMapMan != null) {
37 mBMapMan.destroy();
38 mBMapMan = null;
39 }
40 super.onDestroy();
41 }
42 @Override
43 protected void onPause() {
44 if (mBMapMan != null) {
45 mBMapMan.stop();
46 }
47 super.onPause();
48 }
49 @Override
50 protected void onResume() {
51 if (mBMapMan != null) {
52 mBMapMan.start();
53 }
54 super.onResume();
55 }
56 @Override
57 protected boolean isRouteDisplayed() {
58 // TODO Auto-generated method stub
59 return false;
60 }
61 }
运行结果如下: